-
Notifications
You must be signed in to change notification settings - Fork 1
/
evaluate_reverse_polish_notation.py
40 lines (35 loc) · 1.52 KB
/
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
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
# main idea:
# The Reverse Polish Notation (RPN) is also known as
# the 'postfix' notation, because each operator appears after its operands.
# Stack fits perfectly as it is a Last-In-First-Out (LIFO) data structure.
my_stack = []
operators = ['+', '-', '*', '/']
for token in tokens:
if token not in operators:
operand = int(token) # we need to change it to 'integer'
my_stack.append(operand) # push
else:
a = my_stack.pop()
b = my_stack.pop()
# be careful: need to use 'b-a' and 'b//a'
if token == '+':
c = b + a
my_stack.append(c)
elif token == '-':
c = b - a
my_stack.append(c)
elif token == '*':
c = b * a
my_stack.append(c)
else:
# special case (becasue Python is different from C language)
if b * a < 0:
c = -((-b) // a)
my_stack.append(c)
else:
c = b // a
my_stack.append(c)
final_value = my_stack.pop() # pop the final value in the stack
return final_value