Skip to content

Commit 3c10ae0

Browse files
Merge pull request #3010 from coopers/coopers-0150
Update 0150-evaluate-reverse-polish-notation.py
2 parents 4077d1f + e80b737 commit 3c10ae0

File tree

1 file changed

+25
-13
lines changed

1 file changed

+25
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,29 @@
11
class Solution:
22
def evalRPN(self, tokens: List[str]) -> int:
3+
h = {
4+
'+': self.add,
5+
'-': self.subtract,
6+
'*': self.multiply,
7+
'/': self.divide
8+
}
9+
310
stack = []
4-
for c in tokens:
5-
if c == "+":
6-
stack.append(stack.pop() + stack.pop())
7-
elif c == "-":
8-
a, b = stack.pop(), stack.pop()
9-
stack.append(b - a)
10-
elif c == "*":
11-
stack.append(stack.pop() * stack.pop())
12-
elif c == "/":
13-
a, b = stack.pop(), stack.pop()
14-
stack.append(int(float(b) / a))
15-
else:
16-
stack.append(int(c))
11+
for t in tokens:
12+
if t in h:
13+
b, a = stack.pop(), stack.pop()
14+
t = h[t](a, b)
15+
stack.append(int(t))
16+
1717
return stack[0]
18+
19+
def add(self, a, b):
20+
return a + b
21+
22+
def subtract(self, a, b):
23+
return a - b
24+
25+
def multiply(self, a, b):
26+
return a * b
27+
28+
def divide(self, a, b):
29+
return a / b

0 commit comments

Comments
 (0)