Sub topic 12
Evaluating postfix expressions
This chapter assumes you can write Python functions and lists, and that you know how a stack's push and pop work. You should also be comfortable with O(n) notation.
What postfix is
In infix notation, operators sit between operands: (3 + 4) * 2. Postfix notation, also called reverse Polish notation, puts the operator after its operands: 3 4 + 2 *. Postfix needs no parentheses and no precedence rules. The order of the tokens fixes the order of evaluation.
The algorithm
Scan the tokens from left to right.
- If the token is an operand, push it.
- If the token is an operator, pop two operands, apply the operator, and push the result.
- When the tokens run out, the single value left on the stack is the answer.
The stack fits because an operator always acts on the most recent values, which are the ones on top.
Implementation
def eval_postfix(tokens):
ops = {
"+": lambda a, b: a + b,
"-": lambda a, b: a - b,
"*": lambda a, b: a * b,
"/": lambda a, b: a / b,
}
stack = []
for token in tokens:
if token in ops:
b = stack.pop()
a = stack.pop()
stack.append(ops[token](a, b))
else:
stack.append(float(token))
return stack.pop()
print(eval_postfix(["3", "4", "+", "2", "*"])) # 14.0A dictionary maps each operator to a function, so adding an operator is one new entry. Operands are converted with float, so the result is 14.0 and not 14.
Operand order
The first pop returns the right operand. The second pop returns the left operand. That is why the code assigns b first and then a.
For addition and multiplication the order does not matter. For subtraction and division it does. Take ["10", "4", "-"]. The stack holds 10, 4, so b is 4 and a is 10, and the result is 10 - 4 = 6.0. If you swapped the two pops, you would compute 4 - 10 = -6.0.
Common errors
The function above trusts its input. Malformed input fails in confusing ways.
| Input | What happens | Cause |
|---|---|---|
| `["3", "+"]` | `IndexError: pop from empty list` | An operator has too few operands |
| `["3", "4"]` | Returns `4.0` and ignores `3` | Too many operands, so extra values remain |
| `["3", "x", "+"]` | `ValueError` from `float` | Unknown token treated as a number |
| `["4", "0", "/"]` | `ZeroDivisionError` | Division by zero |
You can check the first two cases by validating the stack. Replace the final return stack.pop() with a check that exactly one value remains:
if len(stack) != 1:
raise ValueError("malformed expression")
return stack.pop()For underflow, catch the IndexError from the pops and raise a ValueError with a clearer message.
Cost
Each token is handled once, and each push or pop is amortized O(1). The whole evaluation is O(n) time. The stack can hold up to O(n) operands in the worst case, for example 1 2 3 4 5 + + + +, so space is O(n).
Exercise
Evaluate the postfix expression 5 1 2 + 4 * + 3 - by hand. What is the stack after each token, and what is the result?
Show answer
After 5: [5]. After 1: [5, 1]. After 2: [5, 1, 2]. After +: [5, 3]. After 4: [5, 3, 4]. After *: [5, 12]. After +: [17]. After 3: [17, 3]. After -: [14]. The result is 14.
Exercise
What does eval_postfix(["8", "2", "/", "3", "-"]) return, and which two pops happen at the / token?
Show answer
At /, the first pop returns 2 (assigned to b) and the second returns 8 (assigned to a), so the result is 8 / 2 = 4.0. Then 3 is pushed and - computes 4.0 - 3.0, so the function returns 1.0.