Reputation: 140
While using sympy.solve() to try and solve simple linear equations, the function just returns an empty list.
Here is my code:
from sympy import Symbol
from sympy.solvers import solve
from sympy.parsing.sympy_parser import parse_expr as parse
x = Symbol('x')
equation = input('Enter an equation: ')
equation = message.content.split()[1].replace('=',',')
solution = solve(parse(equation))
For equation = 'x+3=8'
, print(solution)
just prints []
Can anyone figure out why this is happening?
Thanks!
Upvotes: 1
Views: 234
Reputation: 19145
The standard way to handle this parsing is to use the "battery" transformations:
>>> from sympy.parsing.sympy_parser import parse_expr, T
>>> parse_expr('x=1',transformations=T[1,9]) # auto-symbol and convert =
Eq(x, 1)
>>> solve(_)
[1]
Upvotes: 0
Reputation: 355
I'm not sure what the best practice here is, but using Eq
here will work.
The code after a few changes-
from sympy import Symbol, Eq
from sympy.solvers import solve
from sympy.parsing.sympy_parser import parse_expr as parse
x = Symbol('x')
equation_1 = input('Enter an equation: ')
equation_2 = equation_1.split('=')
solution = solve(Eq(*[parse(i) for i in equation_2]), x)
print(solution)
example output-
Enter an equation: x+1=x**2
[1/2 - sqrt(5)/2, 1/2 + sqrt(5)/2]
Upvotes: 2