-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevalRPN.py
More file actions
33 lines (33 loc) · 1.16 KB
/
evalRPN.py
File metadata and controls
33 lines (33 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
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for i in tokens:
if i != '+' and i != '-' and i != '*' and i != '/':
stack.append(i)
continue
elif i == '+':
num1 = stack.pop()
num2 = stack.pop()
result = int(num2) + int(num1)
stack.append(result)
elif i == '-':
num1 = stack.pop()
num2 = stack.pop()
result = int(num2) - int(num1)
stack.append(result)
elif i == '*':
num1 = stack.pop()
num2 = stack.pop()
result = int(num2) * int(num1)
stack.append(result)
elif i == '/':
num1 = stack.pop()
num2 = stack.pop()
result = int(num2) // int(num1)
if int(num2) // int(num1) >= 0:
stack.append(result)
elif int(num2)%int(num1) == 0:
stack.append(result)
else:
stack.append(result+1)
return stack.pop()