-1

Is there a way to solve math equations that are in string format?

For example, I have x = 2 y = 3 equations_str = ('x+y', 'x-y')

and I want a function that will give

results = (5, -1)

I want to do this because I want to have the equations as titles of figures, so they need to be strings. I'm aware that a similar question was asked for java, but I'm not familiar enough with java so translate it to python.

Thanks!

Kenge
  • 1
  • 1
  • In short, this is a problem that has been dealt with quite a few times. We expect you to do the research and make an attempt before posting here. – Prune Feb 28 '19 at 19:02

4 Answers4

1

Look into eval() https://www.geeksforgeeks.org/eval-in-python/ You can write statements and execute them.

eval example (interactive shell):

>>> x = 1
>>> eval('x + 1')
2
>>> eval('x')
1
1

As Jam mentioned, you can do the following:

equations_str = (eval('x+y'), eval('x-y'))
Young Pattewa
  • 75
  • 2
  • 11
0

The only way I can think of solving this problem is to take your equation, calculate it as a regular integer, and then convert it into a string using str(). Then you could put that result into an array before proceeding. The only thing is that this method won't work for large amounts, but if you only need a few, this should work. Hope this helps, Luke.

-2

Try the sympify function of the sympy package. It lets you evaluate strings, but uses the eval function, so do not use it on unsanitized input.

Example:

>>> from sympy import sympify
>>> str_expr = "x**2 + 3*x - 1/2"
>>> expr = sympify(str_expr)
>>> expr
x**2 + 3*x - 1/2
>>> expr.subs(x, 2)
19/2
JamCon
  • 2,313
  • 2
  • 25
  • 34
IanQ
  • 1,831
  • 5
  • 20
  • 29