Skip to content

Evaluate Reverse Polish Notation

LeetCode

01 · Question

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

02 · Solution

Reference solution

1def evalRPN(tokens: List[str]) -> int:
2 stack = []
3
4 for t in tokens:
5 if t not in {"+", "-", "*", "/"}:
6 stack.append(int(t))
7 continue
8 b = stack.pop()
9 a = stack.pop()
10 if t == "+":
11 stack.append(a + b)
12 elif t == "-":
13 stack.append(a - b)
14 elif t == "*":
15 stack.append(a * b)
16 else:
17 stack.append(int(a / b))
18
19 return stack[-1]