Reputation: 99
I have the following input:
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.
Upvotes: 1
Views: 316
Reputation: 120409
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
Upvotes: 1