python build a dynamic growing truth table

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

提交回复
热议问题