Truth table

From Rosetta Code
Revision as of 07:19, 31 October 2011 by rosettacode>Paddy3118 (New draft task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Truth table is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

A truth table is display of the inputs to, and the output of a boolean equation organised as a table where each row gives one combination of input values and the corresponding value of the equation.

Task
  1. Input a boolean equation from the user as a string then calculate and print a formatted truth table for the given equation.
    (One can assume that the user input is correct).
  2. Print and show output for boolean equations of two and three input variables, but any program should not be limited to that many variables in the equation.
  3. Either reverse-polish or infix notation expressions are allowed.

Python

This accepts correctly formatted Python boolean expressions. <lang python>from itertools import product

while True:

   bexp = input('\nBoolean expression: ')
   bexp = bexp.strip()
   if not bexp:
       print("\nThank you")
       break
   code = compile(bexp, '<string>', 'eval')
   names = code.co_names
   print('\n' + ' '.join(names), ':', bexp)
   for values in product(range(2), repeat=len(names)):
       env = dict(zip(names, values))
       print(' '.join(str(v) for v in values), ':', eval(code, env))

</lang>

Sample output
Boolean expression: A ^ B

A B : A ^ B
0 0 : 0
0 1 : 1
1 0 : 1
1 1 : 0

Boolean expression: S | ( T ^ U )

S T U : S | ( T ^ U )
0 0 0 : 0
0 0 1 : 1
0 1 0 : 1
0 1 1 : 0
1 0 0 : 1
1 0 1 : 1
1 1 0 : 1
1 1 1 : 1

Boolean expression: A ^ (B ^ (C ^ D))

A B C D : A ^ (B ^ (C ^ D))
0 0 0 0 : 0
0 0 0 1 : 1
0 0 1 0 : 1
0 0 1 1 : 0
0 1 0 0 : 1
0 1 0 1 : 0
0 1 1 0 : 0
0 1 1 1 : 1
1 0 0 0 : 1
1 0 0 1 : 0
1 0 1 0 : 0
1 0 1 1 : 1
1 1 0 0 : 0
1 1 0 1 : 1
1 1 1 0 : 1
1 1 1 1 : 0

Boolean expression: 

Thank you