Evaluating postfix
Evaluate a postfix expression with a stack in one pass: a number is pushed, and each operator pops the top two numbers and pushes the result.
In a postfix expression each operator comes right after its operands, so one stack evaluates it in one pass:
Read the full explanation ↓- Time:
O(n) - Space:
O(n) - Horowitz–Sahni, chapter 3
- Johnsonbaugh, chapter 9
62/3-42*+ means (6/2 − 3) + 4·2 = 8.
def evaluate_postfix(expr):# Operands are single digits; / is whole-number division.stack = []for i in range(len(expr)):ch = expr[i]if ch.isdigit():stack.append(int(ch))continueif len(stack) < 2:return Noneb = stack.pop()a = stack.pop()if ch == "+":value = a + belif ch == "-":value = a - belif ch == "*":value = a * belse:if b == 0:return Nonevalue = a // bstack.append(value)if len(stack) != 1:return Nonereturn stack[0]
Start
012345678
62/3-42*+
stack—
Local variables
expr'62/3-42*+'
Orange = changed in this step
Call stack
- evaluate_postfix()line 1
Step 1 of 72
Explanation
The idea
In a postfix expression each operator comes right after its operands, so one stack evaluates it in one pass:
- push a number;
- apply an operator to the top two numbers (the first one popped is the second operand) and push the result.
At the end exactly one number must be left: the answer.
Why a stack?
Each finished subexpression is one number on the stack; an operator always needs the two subexpressions finished last, which are the top two numbers. Compilers and HP calculators work this way.
What to watch in the trace
- Follow the
stackcard; each operator takes two numbers off and puts one back.