This was a homework assignment in my intro-to-data-structures-and-algorithms course. Evaluating an expression in this way is a good exercise. While it’s not literally recursion, I’ve tagged it as such because it uses those ideas. (And there doesn’t seem to be a better category.) These sort of questions, I think, are to Leetcode’s merit: a student (assuming they don’t cheat, of course) can really use this to test their understanding.
Having already known the answer, and not yet subjecting any of my students to this, it’s hard for me to anticipate what the tricky parts of this question are. I assume the key insight is that you can push (what Python calls append) the intermediate values back on the stack and it “just works”. Maybe that follows from reading carefully what RPN is?
The motivation for this problem is that it’s an easy calculator to make, and compilers.
class Solution:
def isOp(self, s):
return s in ['+', '-', '*', '/']
def evalRPN(self, tokens: List[str]) -> int:
stack = []
for t in tokens:
if self.isOp(t):
r = stack.pop()
l = stack.pop()
if t == '+': x = l + r
elif t == '-': x = l - r
elif t == '*': x = l * r
elif t == '/': x = int(l / r)
stack.append(x)
else:
stack.append(int(t))
return stack[0]
Postscript
Is this a good interview question? I don’t know. At a big meeting about interview questions, a work colleague said that they always ask this one as their standard interview question. So that’s one vote! I don’t think there’s trickiness per-se, and I think the parsing and case-handling here is an interesting and good exercise.
I am in parallel trying to build a collection of “classic” problems for students, under this tag.