forked from xharaken/step2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodularized_calculator_original.py
More file actions
executable file
·57 lines (48 loc) · 1.41 KB
/
modularized_calculator_original.py
File metadata and controls
executable file
·57 lines (48 loc) · 1.41 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
#! /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
token = {'type': 'NUMBER', 'number': number}
return token, index
def read_plus(line, index):
token = {'type': 'PLUS'}
return token, index + 1
def tokenize(line):
"""
Tokenize the input line and return a list of tokens
"""
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)
else:
print('Invalid character found: ' + line[index])
exit(1)
tokens.append(token)
return tokens
def evaluate(tokens):
"""
Evaluate the list of tokens and return a calculated result
"""
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']
else:
print('Invalid syntax')
index += 1
return answer
while True:
print('> ', end="")
line = input()
tokens = tokenize(line)
answer = evaluate(tokens)
print("answer = %d\n" % answer)