I'm trying to create a program, that uses sympy to take a set of variables and evaluate a symbolic logic expression over the domain of those variables. The problem is that I cannot get python to evaluate the expression after it spits out the truth table.
Here's the code:
from sympy import *
from sympy.abc import p, q, r
def get_vars():
vars = []
print "Please enter the number of variables to use in the equation"
numVars = int(raw_input())
print "please enter each of the variables on a newline"
for i in xrange(numVars):
vars.append(raw_input())
return vars
def get_expr():
print "Please enter the expression to use"
return str(raw_input())
def convert_to_expr(inputStr):
return eval(inputStr)
def main():
vars = get_vars()
expr = get_expr()
print("recieved input: " + str(vars) + " expr " + str(expr))
print "Truth table for " + str(len(vars)) + "variable(s)"
for i in enumerate(truth_table(vars, expr)):
print i
def fixed_table(numvars):
"""
Generate true/false permutations for the given number of variables.
So if numvars=2
Returns (not necessarily in this order):
True, True
True, False
False, False
False, True
"""
if numvars is 1:
yield [True]
yield [False]
else:
for i in fixed_table(numvars-1):
yield i + [True]
yield i + [False]
def truth_table(vars, expr):
"""
Takes an array of variables, vars, and displays a truth table
for each possible value combination of vars.
"""
for cond in fixed_table(len(vars)):
values=dict(zip(vars,cond))
yield cond + [eval(expr)]
if __name__ == "__main__":
main()
If I do the following, here's the output:
Please enter the number of variables to use in the equation
3
please enter each of the variables on a newline
p
q
r
Please enter the expression to use
p&q&r
recieved input: ['p', 'q', 'r'] expr p&q&r
Truth table for 3variable(s)
(0, [True, True, True, And(p, q, r)])
(1, [True, True, False, And(p, q, r)])
(2, [True, False, True, And(p, q, r)])
(3, [True, False, False, And(p, q, r)])
(4, [False, True, True, And(p, q, r)])
(5, [False, True, False, And(p, q, r)])
(6, [False, False, True, And(p, q, r)])
(7, [False, False, False, And(p, q, r)])
If some software exists to perform this task, I'd really like to know about it :-)
Thanks in advance.