Question

I am trying to make a search function to work with algebra problems. I want something like Wolfram Alpha but I am building a python framework for it. It should be able to figure out multiple variables and equations on both sides of the equal sign. I have recently asked about a validator for the program so I need a loop that goes through a bunch of numbers and figures out what each of the variables equals. My problem is the decimals. I suggest using a search function. Here is the equation solver:

def s_equation(a):
   left, right = a.split('=')
   return eval(left) == eval(right)

Any help is helpful!

Was it helpful?

Solution

The eval()s won't work, because left and right are strings, not expressions. Moreover, you'll have to do substantial validation to make what a user might input a valid Python expression. Consider a few values you might get:

# The typical person's notation for x-squared isn't valid Python
x^2 + x - 3
# 3x means 3 * x to us, but to python it means nothing
3x + 4
# Some people use % to represent division, but that's a modulo operator to Python
3 % 4x
# Python doesn't understand the distributive property
3(4 - x)
# People might use some functions in a way Python doesn't understand
cos x
# Square brackets are used synonymously with parentheses
x[(x^2 - 5)(x^3 - 5x)]

So, in short, you'll need some kind of engine to convert plain text equations into valid Python expressions. This is no easy task, but it can certainly be done.

Although your project is very ambitious, I think it's a great way to use Python! If you come up with an intelligent way to convert equations as strings into valid Python, you should share it immediately because quite a few people in the scientific and math community could have use for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top