-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpn.py
51 lines (38 loc) · 815 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
47
48
49
50
51
#!/usr/bin/env python3
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mult(a, b):
return a * b
def div(a, b):
return a / b
def exp(a, b):
return a ** b
op_table = {
"+": add,
"-": sub,
"*": mult,
"/": div,
"^": exp
}
def calculate(string):
parsed_input = string.split()
stack = []
for token in parsed_input:
try:
stack.append(int(token))
except ValueError:
arg2 = stack.pop()
arg1 = stack.pop()
function = op_table[token]
result = function(arg1, arg2)
stack.append(result)
if len(stack) != 1:
raise TypeError
return stack.pop()
def main():
while True:
calculate(input("rpn calc> "))
if __name__ == '__main__':
main()