-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path736_parse_lisp_expression.py
154 lines (113 loc) · 3.72 KB
/
736_parse_lisp_expression.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
import re
"""
Grammar (LL(2))
expr := let_expr | add_expr | mult_expr | var | int
let_expr := '(' 'let' var_expr_list expr ')'
var_expr_list := var expr var_expr_list | var expr
add_expr := '(' 'add' expr expr ')'
mult_expr := '(' 'mult' expr expr ')'
var := [a-z]([a-zA-Z]|\d)*
int := \d+
"""
class Number(object):
def __init__(self, val): self.val = int(val)
def eval(self, var_map): return self.val
class Variable(object):
def __init__(self, id): self.id = id
def eval(self, var_map): return var_map[self.id]
def __hash__(self): return hash(self.id)
def __repr__(self): return self.id
class Let(object):
def __init__(self, var_list, sub_expr):
self.var_list = var_list
self.sub_expr = sub_expr
def eval(self, var_map):
new_map = dict(var_map)
for var, expr in self.var_list:
new_map[var.id] = expr.eval(new_map)
return self.sub_expr.eval(new_map)
class Add(object):
def __init__(self, a, b):
self.a = a
self.b = b
def eval(self, var_map): return self.a.eval(var_map) + self.b.eval(var_map)
class Mult(object):
def __init__(self, a, b):
self.a = a
self.b = b
def eval(self, var_map): return self.a.eval(var_map) * self.b.eval(var_map)
class LispParser(object):
def __init__(self):
self.tokens = None
self.index = None
def lookahead(self, offset=0):
return self.tokens[self.index + offset]
def consume(self):
token = self.lookahead()
self.index += 1
return token
def parse(self, tokens):
self.tokens = tokens
self.index = 0
return self.parse_expr()
def parse_expr(self):
lookahead = self.lookahead()
if lookahead == '(':
secondlook = self.lookahead(offset=1)
if secondlook == 'let':
return self.parse_let_expr()
elif secondlook == 'add':
return self.parse_add_expr()
elif secondlook == 'mult':
return self.parse_mult_expr()
else:
print('ERROR')
elif lookahead[0].isalpha():
return Variable(self.consume())
else:
return Number(self.consume())
def parse_let_expr(self):
self.consume() # '('
self.consume() # 'let'
var_map = self.parse_var_expr_list()
sub_expr = self.parse_expr()
self.consume() # ')'
return Let(var_map, sub_expr)
def parse_var_expr_list(self):
vars = []
while self.lookahead() != '(' and (self.index + 1 < len(self.tokens)) and self.lookahead(offset=1) != ')':
var = Variable(self.consume())
expr = self.parse_expr()
vars.append([var, expr])
return vars
def parse_add_expr(self):
self.consume() # '('
self.consume() # 'add'
a, b = self.parse_expr(), self.parse_expr()
self.consume() # ')'
return Add(a, b)
def parse_mult_expr(self):
self.consume() # '('
self.consume() # 'mult'
a, b = self.parse_expr(), self.parse_expr()
self.consume() # ')'
return Mult(a, b)
class Solution(object):
def evaluate(self, expression):
token_classes = [
'\(',
'\)',
'let',
'add',
'mult',
'[a-z][a-z0-9]*', # var
'\d+|\-\d+'
]
def scan(): return re.findall('|'.join(token_classes), expression)
parser = LispParser()
tokens = scan()
return parser.parse(tokens).eval({})
if __name__ == '__main__':
s = Solution()
result = s.evaluate('(let x 1 x)')
print(result)