Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solve for x using python

I came across a problem. One string is taken as input say

input_string = "12345 + x = x * 5 + (1+x)* x + (1+18/100)"

And get output of x using python. I am not able to figure out logic for this.

like image 832
Aaroosh Pandoh Avatar asked Sep 19 '26 01:09

Aaroosh Pandoh


1 Answers

Here is a complete SymPy example for your input:

from sympy import Symbol, solve, Eq
from sympy.parsing.sympy_parser import parse_expr

input_string = "12345 + x = x * 5 + (1+x)* x + (1+18/100)"
x = Symbol('x', real=True)
lhs = parse_expr(input_string.split('=')[0], local_dict={'x':x})
rhs = parse_expr(input_string.split('=')[1], local_dict={'x':x})

print(lhs, "=", rhs)
sol = solve(Eq(lhs, rhs), x)
print(sol)
print([s.evalf() for s in sol])

This outputs:

x + 12345 = x*(x + 1) + 5*x + 59/50
[-5/2 + 9*sqrt(15247)/10, -9*sqrt(15247)/10 - 5/2]
[108.630868798908, -113.630868798908]

Note that solve() gives a list of solutions. And that SymPy normally does not evaluate fractions and square roots, as it prefers solutions without loss of precision. evalf() evaluates a float value for these expressions.

like image 174
JohanC Avatar answered Sep 20 '26 16:09

JohanC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!