What is Evaluate RPN
Reverse Polish notation writes the operator after its two numbers. 2 1 + 3 * means (2 + 1) * 3.
Approach
Visualization & algorithm
The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each token is handled once. |
| Space | O(n) | A run of numbers fills the stack. |
Implementation
def solve(self, tokens):
st = []
for t in tokens:
if t in '+-*/':
b = st.pop(); a = st.pop()
if t == '+': st.append(a + b)
elif t == '-': st.append(a - b)
elif t == '*': st.append(a * b)
else: st.append(int(a / b))
else:
st.append(int(t))
return st[-1]