python build a dynamic growing truth table

后端 未结 7 1936
失恋的感觉
失恋的感觉 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 04:57

    returning a datastructure representing the table is fine

    ...in that case range(2 ** n) is all you need. Each number in the range represents a row in the truth table. The ith bit of the binary representation of the number k is 1 if and only if the ith variable is true in the kth row of the table.

    If you want an actual table you can use:

    [ [ ((row >> bit_index) & 1) == 1 for bit_index in range(n)] 
      for bit_index in range(2 ** n) ]
    

提交回复
热议问题