Evaluating a member in an evaluated math expression using python
Here is my question:
Given that I have this form input (string input):
"(x = 5*y + 8) if z<3 else (x=4*y+9))"
I can evaluate this line type using this code:
import parser
formula = "(5*y + 8) if z<3 else (4*y+9)"
code = parser.expr(formula).compile()
y = 10
z=8
print eval(code)
However, in this case, I have no equalities in the expression term.
My question is, is there an easy way to parse the input to create some kind of mathematical expression and then, for example, just give y and z to finally calculate the value of x; and also just let x and z calculate y?
If not, should I turn to abstract syntax trees, and perhaps recursive parsers and grammars? Or is there a library to do this?
Thanks in advance!
source to share
If you can rewrite the formula as valid Python i.e. move the selection to the x
front, you can compile()
also exec
use a special dictionary space:
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
def main():
code = compile('x = (5*y + 8) if z<3 else (4*y+9)', '<main>', 'exec')
namespace = {'y': 10, 'z': 8}
exec code in namespace
print(namespace['x'])
if __name__ == '__main__':
main()
With an argument, the 'exec'
source code assigned compile()
can be anything that can be written to the module.
The command then exec
executes the code with the given dictionary as a namespace, that is, all names used in the compiled code and not defined by the code itself come from this dictionary, and all the names that the code (re) defines are also available from it.
source to share