-1

My problem is: I'd like to get the value of a variable by knowing a Calculation (: "x = 5*x - 20" -> x = 5)

My solution was just Bruteforcing, so I start at 0, and go one up and one down in each step, and check, if it works. It did, but of course that's really slow at float numbers. Over all I need a function like:

getVar(sCalculation ["x = 5*x - 20"], sVar ["x"]) --> 5

How would you do that? If you've got any questions, feel free to ask below:

Machavity
  • 30,841
  • 27
  • 92
  • 100

1 Answers1

0

You will either have to write your own parser that computes x or simply use libraries that do the job for you. There were a lot of discussions about that on SO. For example here: Simplest way to solve mathematical equations in Python.

So basically you should take a look at SymPy's way to solve equations: http://docs.sympy.org/latest/tutorial/solvers.html#solving-equations-algebraically

solve([x = 5*x - 20], [x])
{x: 5}

Edit

Here is another reference that you might want to check: How to calculate expression using sympy in python

Community
  • 1
  • 1
oopbase
  • 11,157
  • 12
  • 40
  • 59