1

So I´m making a basic truth table function. In this example, the formula has 4 values and thus needs 4 loops. Is there any way for me to make a def that takes the number of values in the formula and makes a loop for it?

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))

For instance here the formula has 5 values and needs 5 loops.

def Formula2(a,b,c,d,e):
    return ((not a & b) | (c & b) | (d & (not e)))
Davit Tovmasyan
  • 3,238
  • 2
  • 20
  • 36

1 Answers1

2

Using 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))

Result (table is all the combinations):

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
chepner
  • 497,756
  • 71
  • 530
  • 681
Jonas
  • 1,838
  • 4
  • 19
  • 35