Iterate variables over binary combinations
Is there a simple way to loop variables through all possible combinations of true/false? For example, say we have a function:
def f(a, b, c):
return not (a and (b or c))
Is there a way to loop a,b,c
through 000
, 001
, 010
, 011
, 100
, etc.?
My first thought was to loop through the integers and get the bit that corresponds to the variable position, like so:
for i in range (8):
a = i & 4
b = i & 2
c = i & 1
print(f(a,b,c), " ", a,b,c)
It seems to work, but a
, b
, and c
when printed out are all integers, and integers interact with logical operators differently than booleans. For example, 4 and 2
equals 2
, and 9 or 3
equals 9
. I don't mind it too much, it just took some thinking through to convince myself this doesn't matter.
But the question still stands, is there a still simpler way to loop through all possible true/false or 0/1 values?
Solution 1:
Use itertools.product
:
from itertools import product
for a, b, c in product([True, False], repeat=3):
print(f(a,b,c), " ", a,b,c)
If you really want integers 1 and 0, just replace [True, False]
with [1, 0]
. There's little reason to treat integers as bit arrays here.