I am making an expression parser. I start with the string:
s = 'abs(multiply(4,add(-4,2)))'
and will eventually reach
s = 8
Currently, when I test my code, I reach the print statement and I get
'abc(multiply(4,-2))'
However if I wanted to do this recursively and continue the function, I get this error:
Traceback (most recent call last):
File "test.py", line 44, in <module>
print eval_expr(s)
File "test.py", line 41, in eval_expr
return eval_expr(new_expr)
File "test.py", line 37, in eval_expr
new_expr = str(rest + _2 + value + arg1[arg1.find(')') + 1:])
UnboundLocalError: local variable 'value' referenced before assignment
I'm not sure why I am getting this error. Could someone be an extra pair of eyes and point out why please? Thank you!
code:
from operator import mul, sub, abs, add
s = 'abs(multiply(4,add(-4,2)))'
def eval_expr(expr):
op,_1,arg1 = expr.rpartition('(')
rest,_2,thisop = op.rpartition(',')
args = arg1.rstrip(')').split(',')
j = map(int, args)
if thisop == 'add':
value = str(add(j[0], j[1]))
elif thisop == 'subtract':
value = str(sub(j[0],j[1]))
elif thisop == 'multiply':
value = str(mul(j[0], j[1]))
elif thisop == 'abs':
value = str(abs(j[0]))
new_expr = str(rest + _2 + value + arg1[arg1.find(')') + 1:])
print "new expr: " + new_expr
#if rest:
# return eval_expr(new_expr)
print eval_expr(s)
update
Right now my code gets stuck at the 2nd iteration. The first iteration results in
op = 'abs(multiply(4,add'
_1 = '('
arg1 = '-4,2)))'
rest = 'abs(multiply(4'
_2 = ','
thisop = 'add'
args = ['4','-2']
j = [4,-2]
The second iteration is (using the new expression 'abc(multiply(4,-2))'
op = 'abs(multiply'
_1 = '('
arg1 = '4,-2))'
#Now I dont get any values for rest and _2 but thisop, args, and j are:
thisop = 'abs(multiply'
args = ['4','-2']
j = [4,-2]
I think this is due to the operators inside operators or having 2 integers insider operators.