Skip to content

Commit d5906e8

Browse files
committed
feat: add eval reverse polish notation
1 parent 63f8315 commit d5906e8

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

evalrpn.py

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution(object):
2+
def evalRPN(self, tokens):
3+
stak = []
4+
for i in range(len(tokens)):
5+
if not tokens[i] in "+-*/":
6+
stak.append(int(tokens[i]))
7+
continue
8+
a, b = stak.pop(), stak.pop()
9+
if tokens[i] == "+":
10+
stak.append(b + a)
11+
elif tokens[i] == "-":
12+
stak.append(b - a)
13+
elif tokens[i] == "*":
14+
stak.append(b * a)
15+
elif tokens[i] == "/":
16+
stak.append(int(b / a))
17+
return stak.pop()
18+
19+
20+
if __name__ == "__main__":
21+
s = Solution()
22+
print(s.evalRPN(["2", "1", "+", "3", "*"]))
23+
# => 9 => (2+1)*3
24+
print(
25+
s.evalRPN(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"])
26+
)
27+
# => 22
28+
print(s.evalRPN(["4", "-2", "/", "2", "-3", "-", "-"]))
29+
# => -7

0 commit comments

Comments
 (0)