Foundation drill for this topic
Easy Operand Stack
In plain English: Calculate the result of a math expression written in postfix notation like '2 1 + 3 *'.
Postfix notation eliminates the need for parentheses and precedence — operands are always ready on the stack when an operator appears.
Prompt
Evaluate a postfix (reverse Polish notation) expression.
Try to write it from scratch before scrolling down.
Solution
def eval_postfix(tokens):
stack = []
ops = {'+': lambda a,b: a+b, '-': lambda a,b: a-b,
'*': lambda a,b: a*b, '/': lambda a,b: int(a/b)}
for t in tokens:
if t in ops:
b, a = stack.pop(), stack.pop() # pop order matters: b first, then a
stack.append(ops[t](a, b))
else:
stack.append(int(t))
return stack[0]
# Test: eval_postfix(["2","1","+","3","*"]) == 9
Quick recall drills to reinforce this pattern.
Stack-based expression evaluation is the foundation for calculator and RPN problems.
for tok in tokens:
if tok.lstrip('-').isdigit():
stack.append(int(tok))
else:
b, a = stack.pop(), stack.pop()
if tok == '+': stack.append(a + b)
elif tok == '-': stack.append(a - b)
elif tok == '*': stack.append(a * b)
elif tok == '/': stack.append(int(a / b))
RPN evaluation: numbers push, operators pop two and push result. Note: pop order is b, a (right operand first).
stack = []
for tok in tokens:
if tok in '+-*/':
b, a = stack.pop(), stack.pop()
if tok == '+': stack.append(a + b)
elif tok == '-': stack.append(a - b)
elif tok == '*': stack.append(a * b)
else: stack.append(int(a / b))
else:
stack.append(int(tok))
Stack push/pop is the foundation for all LIFO operations: DFS, undo, and expression parsing.
stack = []
stack.append(x)
stack.pop()