-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path150_evaluate_reverse_polish_notation.py
More file actions
48 lines (35 loc) · 1.16 KB
/
Copy path150_evaluate_reverse_polish_notation.py
File metadata and controls
48 lines (35 loc) · 1.16 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
41
42
43
44
45
46
47
48
from typing import List
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
if len(tokens) == 1:
return int(tokens[0])
else:
operators = ['+', '-', '*', '/']
left_pos = 0
right_pos = 1
op_pos = 2
while tokens[op_pos] not in operators:
left_pos+=1
right_pos+=1
op_pos+=1
left = int(tokens[left_pos])
right = int(tokens[right_pos])
op = tokens[op_pos]
if op == '+':
res = left + right
elif op == '-':
res = left - right
elif op == '*':
res = left * right
else: # Division
if right != 0:
res = int(left / right)
else:
res = 0
tokens = tokens[:left_pos] + [res] + tokens[op_pos+1:]
return self.evalRPN(tokens)
if __name__ == "__main__":
sol = Solution()
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
resultado = sol.evalRPN(tokens)
print(f"Resultado: {resultado}")