forked from wuduhren/leetcode-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate-reverse-polish-notation.py
More file actions
40 lines (35 loc) · 1.12 KB
/
evaluate-reverse-polish-notation.py
File metadata and controls
40 lines (35 loc) · 1.12 KB
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
"""
iterate through the tokens
if the token is +-*/
then take out two operands to calculate with the operator
put the result to stack
(take 2 operands out bc +-*/ are all binary operator)
if the token is operands
put it to stack
the final answer should be the one left in the stack
"""
class Solution(object):
def evalRPN(self, tokens):
def calculate(operator, n1, n2):
if operator=='+':
return n2+n1
elif operator=='-':
return n2-n1
elif operator=='*':
return n2*n1
elif operator=='/' and n1!=0:
#by description
#division between two integers should truncate toward zero.
if n2%n1!=0:
return int(n2/float(n1))
else:
return n2/n1
else:
print('ERROR')
stack = []
for t in tokens:
if t in '+-*/':
stack.append(calculate(t, stack.pop(), stack.pop()))
else:
stack.append(int(t))
return stack.pop()