-2

There are four sensors they're whether on (0) or off (1).

They all can be on or off at the same time.

Example conditions are as below:

A0 0
A1 0
A2 1
A3 0

Another one:

A0 1
A1 1
A2 1
A3 1

How can I print all possible conditions?

I'm writing a code that requires to check which condition is true to do something, and by the time I have wrote ten conditions by thinking. But I think another code can help me to have all conditions.

Saeed
  • 3,255
  • 4
  • 17
  • 36

2 Answers2

4

Use itertools.product. Example:

>>> import itertools
>>> for p in itertools.product((0, 1), repeat=4):
...     for i, v in enumerate(p):
...         print(f"A{i} {v}")
...     print("----")
...
A0 0
A1 0
A2 0
A3 0
----
A0 0
A1 0
A2 0
A3 1
----
A0 0
A1 0
A2 1
A3 0
----
A0 0
A1 0
A2 1
A3 1
----
A0 0
A1 1
A2 0
A3 0
----
A0 0
A1 1
A2 0
A3 1
----
A0 0
A1 1
A2 1
A3 0
----
A0 0
A1 1
A2 1
A3 1
----
A0 1
A1 0
A2 0
A3 0
----
A0 1
A1 0
A2 0
A3 1
----
A0 1
A1 0
A2 1
A3 0
----
A0 1
A1 0
A2 1
A3 1
----
A0 1
A1 1
A2 0
A3 0
----
A0 1
A1 1
A2 0
A3 1
----
A0 1
A1 1
A2 1
A3 0
----
A0 1
A1 1
A2 1
A3 1
----
Samwise
  • 68,105
  • 3
  • 30
  • 44
2

Use itertools.product

>>> list(itertools.product([0, 1], repeat=4))

[(0, 0, 0, 0),
 (0, 0, 0, 1),
 (0, 0, 1, 0),
 (0, 0, 1, 1),
 (0, 1, 0, 0),
 (0, 1, 0, 1),
 (0, 1, 1, 0),
 (0, 1, 1, 1),
 (1, 0, 0, 0),
 (1, 0, 0, 1),
 (1, 0, 1, 0),
 (1, 0, 1, 1),
 (1, 1, 0, 0),
 (1, 1, 0, 1),
 (1, 1, 1, 0),
 (1, 1, 1, 1)]
rafaelc
  • 57,686
  • 15
  • 58
  • 82