Reputation: 343
Here is my question:
Considering I have an input of this form (string input):
"(x = 5*y + 8) if z<3 else (x=4*y+9))"
I can evaluate this kind of string 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 don't have equalities in the member of the expression.
My question is: is there a simple way I parse the input to create some sort of mathematical expression, and then for example, just give y and z to finally compute the value of x; and also just give x and z to compute y?
If not, should I turn myself to abstract syntax trees and maybe recursive parsers and grammars? Or is there a library to do such?
Thanks in advance!
Upvotes: 3
Views: 85
Reputation: 4689
If you can rewrite the formula to be valid Python i.e. moving the assignment to x
in front, then you could compile()
and exec
with a custom namespace dictionary:
#!/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 the 'exec'
argument the source code given to compile()
can be anything that could be written in a module.
The exec
command then executes the code with the given dictionary as namespace, i.e. all names used in the compiled code and not defined by the code itself are coming from this dictionary and all names the code (re)defines are also available from it.
Upvotes: 1