-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpncalc.py
59 lines (45 loc) · 1.5 KB
/
rpncalc.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
import sys
import operator
print "Reverse Polish Notation Calculator. Type 'quit' or 'clear'"
ops = {'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div,
'^': pow}
def calculate(inp_list, operand_stack):
for i in inp_list:
try: operand_stack.append(float(i))
except ValueError:
if i in ops:
if len(operand_stack) < 2:
print "Error: Too many operators. Resetting."
return ['reset']
else:
right = operand_stack.pop()
left = operand_stack.pop()
operand_stack.append(ops[i](left, right))
elif i == 'clear':
return ['reset']
elif i == '':
return operand_stack
elif i == 'quit':
exit()
else:
print "Error: %r is not a valid argument. Resetting." % i
return ['reset']
return operand_stack
operand_stack = []
prompt = "> "
while(True):
inp_list = []
inp_list.extend(raw_input(prompt).split(' '))
operand_stack = calculate(inp_list, operand_stack)
if operand_stack[0] == 'reset':
operand_stack[:] = []
prompt = "> "
elif len(operand_stack) != 1:
print "Error: Not enough operators. Resetting."
operand_stack[:] = []
prompt = "> "
continue
else: prompt = str(operand_stack[0]) + ' '