-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpn.py
46 lines (32 loc) · 804 Bytes
/
rpn.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
#!/usr/bin/env python3
import operator
op = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.floordiv,
'^': operator.pow,
'%': operator.mod
}
def calculate(arg):
stack = arg.split()
while (len(stack) > 1):
token = stack.pop()
try:
value = int(token)
stack.append(value)
except ValueError:
val2 = int(stack.pop())
val1 = int(stack.pop())
func = op[token]
result = func(val1, val2)
stack.append(result);
print (stack[0])
return int(stack[0])
def main():
calcFunc = ''
while calcFunc != 'q':
calcFunc = input("rpn calc> ")
calculate(calcFunc)
if __name__ == '__main__':
main()