简体   繁体   中英

Evaluating a member in an evaluated mathematical expression using python

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!

If you can rewrite the formula to be valid Python ie 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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM