-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpn.py
36 lines (31 loc) · 851 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
#!/usr/bin/env python3
import math
def calculate(arg):
stack = list()
for token in arg.split():
if token == '+':
arg1 = stack.pop()
arg2 = stack.pop()
result = arg1 + arg2
stack.append(result)
elif token == '-':
arg1 = stack.pop()
arg2 = stack.pop()
result = arg2 - arg1
stack.append(result)
elif token == '^':
arg1 = stack.pop()
arg2 = stack.pop()
result = math.pow(arg2, arg1)
stack.append(result)
else:
stack.append(int(token))
print(stack)
if len(stack) != 1:
raise TypeError('Malformed input ' + arg)
return stack.pop()
def main():
while True:
calculate(input("rpn calc> "))
if __name__ == '__main__':
main()