首页 > 解决方案 > 为不同大小制作循环定义

问题描述

所以我正在制作一个基本的真值表函数。在这个例子中,公式有 4 个值,因此需要 4 个循环。我有什么办法可以制作一个 def 来获取公式中的值的数量并为其创建一个循环?

def Formula1(a,b,c,d):
    return ((a & c) | (b & c) | (d & c))

for a in range(0,2):
    for b in range(0,2):
        for c in range(0, 2):
            for d in range(0, 2):
                #printtable(a,b,c,d)
                print(a,b,c,d,"=",Formula1(a,b,c,d))

例如这里的公式有 5 个值,需要 5 个循环。

def Formula2(a,b,c,d,e):
    return ((not a & b) | (c & b) | (d & (not e)))

标签: pythonfunctionloopstruthtable

解决方案


使用itertools

import itertools

def Formula1(a, b, c, d):
    return ((a & c) | (b & c) | (d & c))

if __name__ == '__main__':

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

    for a,b,c,d in table:
        print("{}, {}, {}, {} = {}".format(a, b, c, d, Formula1(a, b, c, d))

结果(table是所有组合):

False, False, False, False = False
False, False, False, True = False
False, False, True, False = False
False, False, True, True = True
False, True, False, False = False
False, True, False, True = False
False, True, True, False = True
False, True, True, True = True
True, False, False, False = False
True, False, False, True = False
True, False, True, False = True
True, False, True, True = True
True, True, False, False = False
True, True, False, True = False
True, True, True, False = True
True, True, True, True = True

推荐阅读