Search code examples
python-3.xstringoptimizationdiscrete-mathematicsprefix-operator

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.


Solution

  • 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.