My question is simple: \"how to build a dynamic growing truth table in python in an elegant way?\"
for n=3
for p in False, True:
for q in False, Tru
List comprehensions are, of course, more Pythonic.
def truthtable (n):
if n < 1:
return [[]]
subtable = truthtable(n-1)
return [ row + [v] for row in subtable for v in [0,1] ]
Results, indented for clairity:
truthtable(1)
[ [0],
[1] ]
truthtable(3)
[ [0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1] ]
As a generator function with yield
:
def truthtable (n):
if n < 1:
yield []
return
subtable = truthtable(n-1)
for row in subtable:
for v in [0,1]:
yield row + [v]
Also simply changing the return from an array comprehension to a generator expression makes the return type equivalent to the yield
version's generator function:
def truthtable (n):
if n < 1:
return [[]]
subtable = truthtable(n-1)
return ( row + [v] for row in subtable for v in [0,1] )