-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator.py
276 lines (219 loc) · 6.71 KB
/
calculator.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#!/usr/local/bin/python2.7
import array
import re
import string
import pdb
######
#TODO:
# enable without whitespace in input string
###########################################################
# UNIT TESTS
#Run unit tests
def Run_All_Tests():
Test_add()
Test_subtract()
Test_add_subtract()
Test_multiply()
Test_divide()
Test_multiply_divide()
Test_exponent()
Test_combos()
Test_misc()
Test_RPN()
def Test_add():
parsed = parse('4 + 56')
template = ['4','56', '+']
assert(parsed == template)
parsed = parse('4 + 56 + 6 + 40')
template = ['4','56','+','6','+','40','+']
assert(parsed == template)
def Test_subtract():
parsed = parse('4 - 56')
template = ['4','56','-']
assert(parsed == template)
parsed = parse('4 - 56 - 6 - 40')
template = ['4','56','-','6','-','40','-']
assert(parsed == template)
def Test_add_subtract():
parsed = parse('4 + 5 - 6')
template = ['4','5','+','6','-']
assert(parsed == template)
parsed = parse('4 + ( 5 - 6 )')
template = ['4','5','6','-','+']
assert(parsed == template)
def Test_multiply():
parsed = parse(' 4 * 87 ')
template = ['4','87','*']
assert(parsed == template)
parsed = parse('3 * 90 * 4')
template = ['3','90','*','4','*']
assert(parsed == template)
def Test_divide():
parsed = parse(' 4 / 87 ')
template = ['4','87','/']
assert(parsed == template)
parsed = parse('3 / 90 / 4')
template = ['3','90','/','4','/']
assert(parsed == template)
def Test_multiply_divide():
parsed = parse('4 * 5 / 56')
template = ['4','5','*','56','/']
assert(parsed == template)
parsed = parse('4 * ( 5 / 32 )')
template = ['4','5','32','/','*']
assert(parsed == template)
parsed = parse('1 * 434345 / 78953 * 21145 / 85241')
template = ['1','434345','*','78953','/','21145','*','85241','/']
assert(parsed == template)
def Test_exponent():
parsed = parse(' 3 ^ 4 ')
template = ['3','4','^']
assert(parsed == template)
parsed = parse(' 3 ^ 4 ^ 5')
template = ['3','4','5','^','^']
assert(parsed == template)
parsed = parse(' 3 ^ ( 4 ^ 5 ) ^ 6')
template = ['3','4','5','^','6','^','^']
assert(parsed == template)
def Test_combos():
parsed = parse('3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3')
template = ['3','4','2','*','1','5','-','2','3','^','^','/','+']
assert(parsed == template)
def Test_misc():
parsed = parse('( ( 4 + 5 ) * 6 )')
template = ['4','5','+','6','*']
assert(parsed == template)
parsed = parse('')
template = []
assert(parsed == template)
def Test_RPN():
inputs = ['5','4','+']
ans = reverse_polish(inputs)
assert(ans == 9)
inputs = ['5','1','2','+','4','*','+','3','-']
ans = reverse_polish(inputs)
assert(ans == 14)
ans = reverse_polish(parse('3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'))
assert(int(ans) == 3)
###########################################################
opers = {
'+': (2,'L'),
'-': (2,'L'),
'*': (3,'L'),
'/': (3,'L'),
'^': (4,'R'),
}
#This function sets up the input string by recognizing whether a
# character is an operator or a number
def setup_input(inp = None):
if inp is None:
inp = raw_input('expression: ')
#remove whitespace and create tokens
tokens = inp.strip().split()
tokenized = []
for token in tokens:
if token in opers:
tokenized.append(('OPER', (token, opers[token][0], opers[token][1])))
elif token == '(' or token == ')':
tokenized.append(('PAREN',token))
elif (token.isdigit() == True):
tokenized.append(('NUM', token))
else:
return 0
return tokenized
#This function will parse the input using the Shunting-yard algorithm
# and yield a string to be interpreted using Reverse Polish notation
def shunting_yard(tokens):
outputQ = []
operstack = []
for token, val in tokens:
"""print '\n'
print "outputQ: "
print outputQ
print "operstack: "
print operstack"""
#if we have a number
if token is 'NUM':
outputQ.append(val)
#if we have an operator
elif token is 'OPER':
t1, prec1, asso1 = val
while operstack and operstack[-1][0] is 'OPER':
t2, prec2, asso2 = operstack[-1][1]
if (asso1 == 'L' and prec1 == prec2) or (prec1 < prec2):
outputQ.append(operstack.pop()[1][0])
else:
break
operstack.append((token,val))
elif val == '(':
operstack.append((token,val))
elif val == ')':
try:
while operstack[-1][0] is not 'PAREN':
outputQ.append(operstack.pop()[1][0])
except KeyError:
return -1
operstack.pop()
while operstack:
t2, val = operstack.pop()
if t2 is 'PAREN':
return -1
outputQ.append(val[0])
return outputQ
#This function will take an input in posfix notation and apply the
# Reverse Polish Notation algorithm to yield an solution
def reverse_polish(inputs):
stack = []
for token in inputs:
if token in opers:
stack = handle_oper(token,stack)
else:
stack.append(float(token))
if len(stack) == 1:
return stack[0]
else:
return -1
def handle_oper(oper,stack):
one = stack.pop()
two = stack.pop()
if oper == '+':
stack.append(one + two)
elif oper == '-':
stack.append(two - one)
elif oper == '*':
stack.append(one * two)
elif oper == '/':
stack.append(two / one)
else:
stack.append(two ** one)
return stack
def parse(rawstring):
tokenized = setup_input(rawstring)
if tokenized == 0:
print "Invalid input"
return False
formatted = shunting_yard(tokenized)
return formatted
#Main
def main():
print "#########################################################"
print "First we run unit tests"
print "..."
Run_All_Tests()
print "Done with unit tests"
print "#########################################################"
#create game board
print "\nWelcome to the Calculator"
while True:
#Capture user input string
rawstring = raw_input("Enter your calculation: ")
print("Your input was: " + rawstring)
formatted = parse(rawstring)
if formatted == -1:
print "Error! You had unmatched parenthesis. Try again"
else:
print formatted
ans = reverse_polish(formatted)
print ans
print "\n"
main()