Python: Eval with undefined variables (2*x+x = 3*x)

275 views Asked by At

I'm looking for a way, to calculate strings, that might include variables. eval won't do the job, as I want to use undefined variables. I'm talking about a function, that would turn "2*3*x" to "6*x" for example.

Is there a function for that?

2

There are 2 answers

4
unutbu On BEST ANSWER

You could use sympy for symbolic computation:

In [126]: import sympy as sy

In [127]: sy.simplify('2*x+x')
Out[127]: 3*x

To convert rationals to floats, use sy.nfloat:

In [170]: sy.nfloat(sy.simplify('2*3+x+3/4'))
Out[170]: x + 6.75
4
Joe T. Boka On

I maybe misunderstand your question completely but you said in your OP that: I'm talking about a function, that would turn 2*3*x to 6*x If this is what you need then it's very easy, just use parenthesis :

(2*3)*x