【问题标题】:Make loop def for varying sizes为不同大小制作循环定义
【发布时间】:2019-07-25 01:49:19
【问题描述】:

所以我正在制作一个基本的真值表函数。在这个例子中,公式有 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)))

【问题讨论】:

    标签: python function loops truthtable


    【解决方案1】:

    使用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
    

    【讨论】:

    • @AronGarðarMasson 在这种情况下请接受答案 ;)
    猜你喜欢
    • 1970-01-01
    • 2012-10-27
    • 2020-05-30
    • 2015-02-22
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多