python build a dynamic growing truth table

后端 未结 7 1939
失恋的感觉
失恋的感觉 2021-02-07 04:36

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         


        
相关标签:
7条回答
  • 2021-02-07 05:03

    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] )
    
    0 讨论(0)
提交回复
热议问题