abstract syntax tree - replace variable names with actual values in an expression in AST python -



abstract syntax tree - replace variable names with actual values in an expression in AST python -

i have look described in variable forms this

's1*3 - (s2-s1)*1'

i have given values of s1 , s2 can alter according need

i can utilize python ast module evaluate look replacing respective s1 , s2 values (s1 = 20,s2=30)

import ast import operator op operators = {ast.add: op.add, ast.sub: op.sub, ast.mult: op.mul, ast.div: op.truediv, ast.pow: op.pow, ast.bitxor: op.xor, ast.usub: op.neg} def eval_(node): if isinstance(node, ast.num): # <number> homecoming node.n elif isinstance(node, ast.binop): # <left> <operator> <right> homecoming operators[type(node.op)](eval_(node.left), eval_(node.right)) elif isinstance(node, ast.unaryop): # <operator> <operand> e.g., -1 homecoming operators[type(node.op)](eval_(node.operand)) else: raise typeerror(node) >>> str1 = '20*3 - (30-20)*1' >>> node = ast.parse(str1, mode='eval') >>> eval_(node.body) 50

how should evaluate look without need replace variables actual values.

thanks

you can utilize eval function . must careful using eval because execute string, can unsafe if take strings evaluate untrusted input. illustration suppose string beingness evaluated "os.system('rm -rf /')" ? start deleting files on computer.

>>> eval('20*3 - (30-20)*1') 50

as improve solution can parse equation python's internal compiler :

>>> s1=20 >>> s2=30 >>> eq='s1*3 - (s2-s1)*1' >>> compiler.parse( eq ) module(none, stmt([discard(sub((mul((name('s1'), const(3))), mul((sub((name('s2'), name('s1'))), const(1))))))]))

so if want evaluate equation , more safer using input can utilize compile , eval !

>>> eq='s1*3 - (s2-s1)*1' >>> a=compile(eq,'','eval') >>> eval(a) 50

also can utilize sympy python library symbolic mathematics. aims become full-featured computer algebra scheme (cas) while keeping code simple possible in order comprehensible , extensible. sympy written exclusively in python , not require external libraries.

python abstract-syntax-tree

Comments

Popular posts from this blog

xslt - DocBook 5 to PDF transform failing with error: "fo:flow" is missing child elements. Required content model: marker* -

mediawiki - How do I insert tables inside infoboxes on Wikia pages? -

Local Service User Logged into Windows -