python build a dynamic growing truth table

后端 未结 7 1924
失恋的感觉
失恋的感觉 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:37

    Use itertools.product():

    table = list(itertools.product([False, True], repeat=n))
    

    Result for n = 3:

    [(False, False, False),
     (False, False, True),
     (False, True, False),
     (False, True, True),
     (True, False, False),
     (True, False, True),
     (True, True, False),
     (True, True, True)]
    
    0 讨论(0)
  • 2021-02-07 04:41

    who here likes raw 1-liners?

    >>> truthtable = lambda n: [[(v>>i)&1 for i in range(n-1,-1,-1)] for v in range(1<<n)] if n>0 else [[]]
    

    100% tested and working.
    (can't copy/paste result, or above code, cause I'm on a phone for Internet)

    0 讨论(0)
  • 2021-02-07 04:44

    itertools really is the way to go as has been pointed out by everyone. But if you really want to see the nuts and bolts of the algorithm required for this, you should look up recursive descent. Here's how it would work in your case:

    def tablize(n, truths=[]):
        if not n:
            print truths
        else:
            for i in [True, False]:
                tablize(n-1, truths+[i])
    

    Tested, working

    Hope this helps

    0 讨论(0)
  • 2021-02-07 04:47

    Have a look at the itertools module

    In [7]: [i for i in itertools.product([0,1], repeat=3)]
    Out[7]: 
    [(0, 0, 0),
     (0, 0, 1),
     (0, 1, 0),
     (0, 1, 1),
     (1, 0, 0),
     (1, 0, 1),
     (1, 1, 0),
     (1, 1, 1)]
    
    0 讨论(0)
  • 2021-02-07 04:47

    Easy math aproach:

    a = lambda x: [x//4%2,x//2%2,x%2]
    
    for i in range(8):
        print(a(i))
    
    [0, 0, 0]
    [0, 0, 1]
    [0, 1, 0]
    [0, 1, 1]
    [1, 0, 0]
    [1, 0, 1]
    [1, 1, 0]
    [1, 1, 1]
    

    EDIT:

    A more general format wold be:

    def truth_table(n):
        for i in range(2**n):
            line = [i//2**j%2 for j in reversed(range(n))]
            print(line)
    

    This will only print the result as:

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