-
Notifications
You must be signed in to change notification settings - Fork 1
/
calculator_expected.py
242 lines (207 loc) · 6.73 KB
/
calculator_expected.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
#! /usr/bin/python3
# Run this program with python3 (not python2)
def read_number(line, index):
number = 0
flag = 0
keta = 1
while index < len(line) and (line[index].isdigit() or line[index] == '.'):
if line[index] == '.':
flag = 1
else:
number = number * 10 + int(line[index])
if flag == 1:
keta *= 0.1
index += 1
token = {'type': 'NUMBER', 'number': float(number * keta)}
return token, index
def read_function(line, index):
for name in ["abs", "int", "round"]:
if line[index : index + len(name)] == name:
token = {'type': 'FUNCTION', 'name': name}
return token, index + len(name)
print('Unknown function found: ' + line[index])
exit(1)
def read_plus(line, index):
token = {'type': 'PLUS'}
return token, index + 1
def read_minus(line, index):
token = {'type': 'MINUS'}
return token, index + 1
def read_multiply(line, index):
token = {'type': 'MULTIPLY'}
return token, index + 1
def read_divide(line, index):
token = {'type': 'DIVIDE'}
return token, index + 1
def read_left(line, index):
token = {'type': 'LEFT'}
return token, index + 1
def read_right(line, index):
token = {'type': 'RIGHT'}
return token, index + 1
def tokenize(line):
tokens = []
index = 0
while index < len(line):
if line[index].isdigit():
(token, index) = read_number(line, index)
elif line[index].isalpha():
(token, index) = read_function(line, index)
elif line[index] == '+':
(token, index) = read_plus(line, index)
elif line[index] == '-':
(token, index) = read_minus(line, index)
elif line[index] == '*':
(token, index) = read_multiply(line, index)
elif line[index] == '/':
(token, index) = read_divide(line, index)
elif line[index] == '(':
(token, index) = read_left(line, index)
elif line[index] == ')':
(token, index) = read_right(line, index)
else:
print('Invalid character found: ' + line[index])
exit(1)
tokens.append(token)
return tokens
def evaluate_brackets(tokens):
index = 0
bracket_left_index = 0
while index < len(tokens):
# Find the leftmost ')'
if tokens[index]['type'] == 'RIGHT':
for i in reversed(range(0, index)):
# Find the corresponding '('
if tokens[i]['type'] == 'LEFT':
left_index = i
break
# Evaluate an expression inside the bracket
value = evaluate(tokens[left_index + 1 : index])
tokens[index] = {'type': 'NUMBER', 'number': value}
del tokens[left_index : index]
index = left_index
index += 1
return tokens
def evaluate_multiply_and_divide(tokens):
index = 0
while index < len(tokens):
if tokens[index]['type'] == 'MULTIPLY':
num = tokens[index - 1]['number'] * tokens[index + 1]['number']
del tokens[index - 1 : index + 2]
tokens.insert(index - 1, {'type': 'NUMBER', 'number': num})
elif tokens[index]['type'] == 'DIVIDE':
num = tokens[index - 1]['number'] * 1.0 / tokens[index + 1]['number']
del tokens[index - 1 : index + 2]
tokens.insert(index - 1, {'type': 'NUMBER', 'number': num})
else:
index += 1
return tokens
def evaluate_functions(tokens):
index = 0
while index < len(tokens):
if tokens[index]['type'] == 'FUNCTION':
if tokens[index]['name'] == "abs":
num = abs(tokens[index + 1]['number'])
elif tokens[index]['name'] == "int":
num = int(tokens[index + 1]['number'])
elif tokens[index]['name'] == "round":
num = round(tokens[index + 1]['number'])
del tokens[index : index + 2]
tokens.insert(index, {'type': 'NUMBER', 'number': num})
else:
index += 1
return tokens
def evaluate_plus_and_minus(tokens):
answer = 0
tokens.insert(0, {'type': 'PLUS'}) # Insert a dummy '+' token
index = 1
while index < len(tokens):
if tokens[index]['type'] == 'NUMBER':
if tokens[index - 1]['type'] == 'PLUS':
answer += tokens[index]['number']
elif tokens[index - 1]['type'] == 'MINUS':
answer -= tokens[index]['number']
else:
print('Invalid syntax')
exit(1)
index += 1
return answer
def evaluate(tokens):
tokens = evaluate_brackets(tokens)
tokens = evaluate_functions(tokens)
tokens = evaluate_multiply_and_divide(tokens)
return evaluate_plus_and_minus(tokens)
def test(line):
tokens = tokenize(line)
actual_answer = evaluate(tokens)
expected_answer = eval(line)
if abs(actual_answer - expected_answer) < 1e-8:
print("PASS! (%s = %f)" % (line, expected_answer))
else:
print("FAIL! (%s should be %f but was %f)" % (
line, expected_answer, actual_answer))
# Add more tests to this function :)
def run_test():
print("==== Test started! ====")
test("1")
test("11")
test("2+3")
test("2-3")
test("2*3")
test("2/3")
test("2+3+4")
test("2-3-4")
test("2*3+4")
test("2+3*4")
test("2/3+4")
test("2+3/4")
test("2*3-4*5-6/7+8/9")
test("11.1")
test("1.1+2.2")
test("1.1-2.2")
test("1.1*2.2")
test("1.1/2.2")
test("1.1*2.2-3.3*4.4-5.5/6.6+7.7/8.8")
test("(1)")
test("(1+2)")
test("((1))")
test("((1.1))")
test("(1+2)*3")
test("(1+2)/3")
test("1*(2+3)")
test("1/(2+3)")
test("(1+2)*(3+4)")
test("(1+2)/(3+4)")
test("1-(2-3)")
test("1-(2-(3-4))")
test("1-(2-(3-(4-5)))")
test("1-(2-(3-(4-5)-6))")
test("1-(2-(3-(4-5)-6))")
test("1-(2-(3-(4-5)-6)-7)")
test("1-(2-(3-(4-5)-6)-7)-8")
test("(1+2)*3-4/(5-(6-7*8+9/(10-11)*12))")
test("(1.1+2.2)*3.3-4.4/(5.5-(6.5-7.7*8.8+9.9/(10.0-11.1)*12.2))")
test("abs(2.1)")
test("abs(-2.1)")
test("abs(0)")
test("round(1)")
test("round(1.1)")
test("round(1.4999)")
test("round(1.5001)")
test("round(-1.5001)")
test("int(1)")
test("int(1.01)")
test("int(-1.01)")
test("abs(abs(-1.5))")
test("round(round(-1.5))")
test("int(int(-1.5))")
test("abs(int(round(-1)))")
test("round((1.1+2.2)*3.3)-int(4.4)/(abs(int(5.5-round(6.5-7.7*8.8+int(9.9/(10.0-11.1)*12.2)))))")
print("==== Test finished! ====\n")
run_test()
while True:
print('> ', end="")
line = input()
tokens = tokenize(line)
answer = evaluate(tokens)
print("answer = %f\n" % answer)