forked from xharaken/step2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodularized_calculator.py
More file actions
executable file
·87 lines (72 loc) · 2.29 KB
/
modularized_calculator.py
File metadata and controls
executable file
·87 lines (72 loc) · 2.29 KB
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
#! /usr/bin/python3
def read_number(line, index):
number = 0
while index < len(line) and line[index].isdigit():
number = number * 10 + int(line[index])
index += 1
if index < len(line) and line[index] == '.':
index += 1
decimal = 0.1
while index < len(line) and line[index].isdigit():
number += int(line[index]) * decimal
decimal /= 10
index += 1
token = {'type': 'NUMBER', 'number': number}
return token, index
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 tokenize(line):
tokens = []
index = 0
while index < len(line):
if line[index].isdigit():
(token, index) = read_number(line, index)
elif line[index] == '+':
(token, index) = read_plus(line, index)
elif line[index] == '-':
(token, index) = read_minus(line, index)
else:
print('Invalid character found: ' + line[index])
exit(1)
tokens.append(token)
return tokens
def evaluate(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 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+2")
test("1.0+2.1-3")
print("==== Test finished! ====\n")
run_test()
while True:
print('> ', end="")
line = input()
tokens = tokenize(line)
answer = evaluate(tokens)
print("answer = %f\n" % answer)