I have ten systems, A, B, C, ..., J. Each system can be up or down. If, for example, systems A, B, D and J are down, with the remainder being up then I want to take action X. If systems C, D, and H are down, with the remainder being up then I want to take action Y. If systems A, E, F, H and I are down, with the remainder being up then I want to take action Z.
I am wanting to write a program that will print the various combinations (I believe with 10 systems and each can be up or down there are 100 combinations).
I have this so far:
import itertools
status_list = (
"Up",
"Down",
)
component_list = (
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"G",
"I",
"J",
)
combinations = itertools.product(component_list, status_list)
If you don't mind using a binary representation, we could use 0
to represent Up
and 1
to represent Down
Our values would range from 0
, to 10^2-1
,
which is 0
to 1023
, or
0000000000
to 1111111111
.
So we could just loop from 0 to 1023, printing the numbers out in a 10-digit binary format:
for x in range(2**10):
print '{0:010b}'.format(x)
Outputs:
0000000000
0000000001
0000000010
0000000011
0000000100
0000000101
0000000110
...etc
If you wanted to get fancier and print up
and down
instead of 0
and 1
, you could examine the digits one-by-one and convert:
for x in range(2**10):
#Iterate over each character c in the binary number x
#Convert c to an int
#Look up the value in status_list by taking c mod length of status list
print(" ".join(status_list[int(c)%len(status_list)] for c in '{0:010b}'.format(x)))
Outputs:
Up Up Up Up Up Up Up Up Up Up
Up Up Up Up Up Up Up Up Up Down
Up Up Up Up Up Up Up Up Down Up
Up Up Up Up Up Up Up Up Down Down
You can print out every possible combination of Up
and Down
using itertools.product
:
import itertools
components = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
statuses = ['Up', 'Down']
for state in itertools.product(statuses, repeat=len(components)):
for c,s in zip(components, state):
print '{}:{}'.format(c,s),
print
This produces output like the following:
A:Up B:Up C:Up D:Up E:Up F:Up G:Up H:Up I:Up J:Up
A:Up B:Up C:Up D:Up E:Up F:Up G:Up H:Up I:Up J:Down
...
A:Up B:Down C:Down D:Down E:Down F:Down G:Down H:Down I:Down J:Up
A:Up B:Down C:Down D:Down E:Down F:Down G:Down H:Down I:Down J:Down
A:Down B:Up C:Up D:Up E:Up F:Up G:Up H:Up I:Up J:Up
A:Down B:Up C:Up D:Up E:Up F:Up G:Up H:Up I:Up J:Down
...
A:Down B:Down C:Down D:Down E:Down F:Down G:Down H:Down I:Down J:Up
A:Down B:Down C:Down D:Down E:Down F:Down G:Down H:Down I:Down J:Down
It deals nicely with a variable number of components or states (for example, you could make states = ['Up', 'Down', 'Unknown']
and you would get 3^10 = 59049 outputs).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.