-
Notifications
You must be signed in to change notification settings - Fork 0
/
6-interpreting.py
37 lines (24 loc) · 937 Bytes
/
6-interpreting.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Write an eval_exp procedure to interpret JavaScript arithmetic expressions.
# Only handle +, - and numbers for now.
def eval_exp(tree):
# ("number" , "5")
# ("binop" , ... , "+", ... )
nodetype = tree[0]
if nodetype == "number":
return int(tree[1])
elif nodetype == "binop":
left_child = tree[1]
operator = tree[2]
right_child = tree[3]
left_val = eval_exp(left_child)
right_val = eval_exp(right_child)
if operator == "+":
return left_val + right_val
elif operator == "-":
return left_val - right_val
test_tree1 = ("binop",("number","5"),"+",("number","8"))
print eval_exp(test_tree1) == 13
test_tree2 = ("number","1776")
print eval_exp(test_tree2) == 1776
test_tree3 = ("binop",("number","5"),"+",("binop",("number","7"),"-",("number","18")))
print eval_exp(test_tree3) == -6