-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path150 Evaluate Reverse Polish Notation.py
54 lines (47 loc) · 1.46 KB
/
150 Evaluate Reverse Polish Notation.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
Author: Rajeev Ranjan
"""
class Solution(object):
def evalRPN(self, tokens):
"""
stack
basic in bytecode operation
basic in compiler technique
:param tokens:
:return:
"""
ops = ["+", "-", "*", "/"]
def arith(a, b, op):
if (op == "+"):
return a+b
if (op == "-"):
return a-b
if (op == "/"):
# return a/b # python treat differently for division 6/-132 is -1
return int(float(a)/b) # round towards 0
if (op == "*"):
return a*b
# function is first-order class
# not supported by leetcode
# import operator
# ops = {
# "+": operator.add,
# "-": operator.sub,
# "*": operator.mul,
# "/": operator.div,
# }
#
# def arith(a, b, op):
# return ops[op](a, b)
# stack
stack = []
for token in tokens:
if token not in ops:
stack.append(int(token))
else:
arg2 = stack.pop()
arg1 = stack.pop()
result = arith(arg1, arg2, token)
stack.append(result)
return stack.pop()
if __name__ == "__main__":
assert Solution().evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) == 22