Rather than starting with lexing and parsing, this week we just assume we have those bits already working, so that we can jump straight to eval()
.
diagrams used during the meeting:
Rather than starting with lexing and parsing, this week we just assume we have those bits already working, so that we can jump straight to eval()
.
diagrams used during the meeting:
#!/usr/bin/env python | |
def add(a,b): | |
return a + b | |
def multiply(a,b): | |
return a * b | |
def flookup(toktype): | |
if toktype == "plus": | |
return add | |
elif toktype == "mult": | |
return multiply | |
def matheval(node): | |
if node["token"]["type"] == "num": | |
return float(node["token"]["text"]) | |
else: | |
f = flookup(node["token"]["type"]) | |
l = matheval(node["left"]) | |
r = matheval(node["right"]) | |
return f(l,r) | |
t1 = { "type": "num", "text": "1" } | |
tp = { "type": "plus", "text": "+" } | |
t2 = { "type": "num", "text": "2" } | |
tm = { "type": "mult", "text": "*" } | |
t3 = { "type": "num", "text": "3" } | |
n1 = { "token": t1, "left": None, "right": None } | |
np = { "token": tp, "left": None, "right": None } | |
n2 = { "token": t2, "left": None, "right": None } | |
nm = { "token": tm, "left": None, "right": None } | |
n3 = { "token": t3, "left": None, "right": None } | |
# * | |
# / \ | |
# + 3 | |
# / \ | |
# 1 2 | |
tree = nm | |
nm["left"] = np | |
nm["right"] = n3 | |
np["left"] = n1 | |
np["right"] = n2 | |
print matheval(tree) # 9 | |
# + | |
# / \ | |
# 1 * | |
# / \ | |
# 2 3 | |
tree = np | |
np["left"] = n1 | |
np["right"] = nm | |
nm["left"] = n2 | |
nm["right"] = n3 | |
print matheval(tree) # 7 |