-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluate_reverse_polish_notation.py
64 lines (58 loc) · 2.09 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
# git add . && git commit -m "completed evaluate_reverse_polish_notation" && git push && exit
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = deque()
for token in tokens:
if token in ['*','-','+','/']:
another = stack.pop()
result = stack.pop()
if token == '+':
result += another
elif token == '-':
result -= another
elif token == '/':
result = result/another
if result < 0:
result = math.ceil(result)
else:
result = math.floor(result)
elif token == '*':
result *= another
stack.append(result)
else:
stack.append(int(token))
return stack.pop()
# faster version
# class Solution:
# def evalRPN(self, tokens: List[str]) -> int:
# stack = deque()
# for token in tokens:
# if token == '+':
# another = stack.pop()
# result = stack.pop()
# result += another
# stack.append(result)
# elif token == '-':
# another = stack.pop()
# result = stack.pop()
# result -= another
# stack.append(result)
# elif token == '/':
# another = stack.pop()
# result = stack.pop()
# result = result/another
# if result < 0:
# result = math.ceil(result)
# else:
# result = math.floor(result)
# stack.append(result)
# elif token == '*':
# another = stack.pop()
# result = stack.pop()
# result *= another
# stack.append(result)
# else:
# stack.append(int(token))
#
# return stack.pop()