PYTHON
95
eval
Guest on 30th April 2022 11:59:56 PM
def eval(t) :
"""pre: t is a TREE,
where TREE ::= NUMERAL | [ OP, TREE1, TREE2 ]
OP is "+" or "-"
NUMERAL is a string of digits
post: ans is the numerical meaning of t
"""
print "Eval", t
if isinstance(t, str) and t.isdigit() : #is t a NUMERAL ?
ans = int(t)
else : # t is a list, [op, t1, t2]
op = t[0]
t1 = t[1]
t2 = t[2]
ans1 = eval(t1)
# assert: ans1 is the numerical meaning of t1
ans2 = eval(t2)
# assert: ans2 is the numerical meaning of t2
if op == "+" :
ans = ans1 + ans2
elif op == "-" :
ans = ans1 - ans2
print "The value of", t, "is", ans
return ans