python build a dynamic growing truth table

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

提交回复
热议问题