Reputation:
Thanks in advance!
I am writing a program to check if a
is true and then return True or False. I need to split it up at the equal sign and then check if the 1st item in the list is equal to the second item and vise-versa. Here is what I have so far:
def s_equation(a):
equal=a.split("=")
Upvotes: 0
Views: 3571
Reputation: 6441
You don't really give enough information to answer your question well. Do you want to test it as an identity (ie test the algebra) or as an instantaneous equality?
For the former, (install sympy first):
import sympy
def s_equation(a):
x = sympy.Symbol('x')
y = sympy.Symbol('y')
left, right = a.split('=')
return eval (left + '==' + right)
usage:
s_equation('x+x = x*2')
#True
s_equation('x+y**2 = y+x**2')
#False
Upvotes: 0
Reputation: 123632
left, right = a.split("=")
assert left == right
You're gonna need to give us more details than that if you want a useful answer. Are you trying to write a full computer algebra system (like e.g. Mathematica)? That's a biiiiig project and has already been done several times. Consider using something like Sage
.
Edit: math beat me to the punch, although I would recommend using ast.literal_eval
instead of eval
unless you trust the input you will receive.
Upvotes: 4
Reputation: 2881
You can use eval() to evaluate each part of the equation:
def s_equation(a):
left, right = a.split('=')
return eval(left) == eval(right)
Some tests:
>>> s_equation('1+1+1=3')
True
>>> s_equation('2*2=8')
False
Upvotes: 3