You are really near! When you have And(p, q, r) and your truth tables, you can use the subs method to push your values tag to the expression: ie
yield cond + [eval(expr).subs(values)]
gives
p&q&r recieved input: ['p', 'q', 'r'] expr p&q&r Truth table for 3variable(s) (0, [True, True, True, True]) (1, [True, True, False, False]) (2, [True, False, True, False]) (3, [True, False, False, False]) (4, [False, True, True, False]) (5, [False, True, False, False]) (6, [False, False, True, False]) (7, [False, False, False, False])
But I think there is an easier way to do this. The sympify function already works to generate expressions from strings:
In [7]: expr = sympify("x & y | z") In [8]: expr Out[8]: Or(z, And(x, y))
and we can also get variables:
In [9]: expr.free_symbols Out[9]: set([x, z, y])
plus itertools.product can generate values (and cartes is an alias for it in sympy ):
In [12]: cartes([False, True], repeat=3) Out[12]: <itertools.product at 0xa24889c> In [13]: list(cartes([False, True], repeat=3)) Out[13]: [(False, False, False), (False, False, True), (False, True, False), (False, True, True), (True, False, False), (True, False, True), (True, True, False), (True, True, True)]
Combining them, which mainly use sympify to get the expression and avoid eval , using the built-in Cartesian product and adding .subs() to use your values dictionary, we get:
def explore(): expr_string = raw_input("Enter an expression: ") expr = sympify(expr_string) variables = sorted(expr.free_symbols) for truth_values in cartes([False, True], repeat=len(variables)): values = dict(zip(variables, truth_values)) print sorted(values.items()), expr.subs(values)
which gives
In [22]: explore() Enter an expression: a & (b | c) [(a, False), (b, False), (c, False)] False [(a, False), (b, False), (c, True)] False [(a, False), (b, True), (c, False)] False [(a, False), (b, True), (c, True)] False [(a, True), (b, False), (c, False)] False [(a, True), (b, False), (c, True)] True [(a, True), (b, True), (c, False)] True [(a, True), (b, True), (c, True)] True
This is less than yours, but it uses exactly your approach.