Search code examples
pythonfunctionuser-inputnumerical-methodspolynomials

How to convert a polynomial user input into python readable form


I have the following input:

enter image description here

and I want to convert it into python readable form like this 'x**2 + 2*x + 2' so that I can use it as an input to other functions. I have:

def func_parse(func):
    return func.replace("^","**")

but this will only resolve the power part. I also want to add '*' in between '2x' to conform with the python syntax.


Solution

  • Install sympy:

    from sympy.parsing.sympy_parser import (
        parse_expr, stringify_expr, standard_transformations,
        implicit_multiplication_application, convert_xor
    )
    
    transformations = (standard_transformations 
                       + (implicit_multiplication_application, convert_xor))
    
    f = 'x^2 + 2x + 3'
    expr = parse_expr(f, transformations=transformations)
    

    Output:

    >>> str(expr)
    'x**2 + 2*x + 3'
    

    Update

    Evaluate the polynomial output with an integer value, let's say (x =2).

    >>> expr.evalf(subs=dict(x=2))
    11.0000000000000