Sub topic 13
Converting infix to postfix
This chapter assumes you know how a stack works (push, pop, peek) and have read the previous chapter on evaluating postfix expressions. Here you will build the other half: turning ordinary infix expressions like (3 + 4) * 2 into postfix form, so the evaluator can run them.
Why convert
Infix puts operators between operands, so you need precedence and parentheses to know the order of work. Postfix puts operators after their operands, so the order is already fixed. Converting once lets you evaluate with a simple loop and no precedence rules.
| Infix | Postfix |
|---|---|
| `3 + 4 * 2` | `3 4 2 * +` |
| `(3 + 4) * 2` | `3 4 + 2 *` |
| `8 - 3 - 2` | `8 3 - 2 -` |
The shunting-yard idea
Edsger Dijkstra's shunting-yard algorithm scans the tokens left to right. It uses an output list and an operator stack.
- An operand goes straight to the output.
- An operator first pops any operators on the stack with equal or higher precedence, sending them to the output. Then it is pushed.
- A
(is pushed. - A
)pops operators to the output until the matching(, which is discarded. - At the end, pop everything left on the stack to the output.
Implementation
PRECEDENCE = {"+": 1, "-": 1, "*": 2, "/": 2}
def infix_to_postfix(tokens):
output = []
stack = []
for token in tokens:
if token in PRECEDENCE:
while (stack and stack[-1] != "("
and PRECEDENCE[stack[-1]] >= PRECEDENCE[token]):
output.append(stack.pop())
stack.append(token)
elif token == "(":
stack.append(token)
elif token == ")":
while stack and stack[-1] != "(":
output.append(stack.pop())
if not stack:
raise ValueError("unmatched )")
stack.pop() # discard the "("
else:
output.append(token)
while stack:
top = stack.pop()
if top == "(":
raise ValueError("unmatched (")
output.append(top)
return output
print(infix_to_postfix(["3", "+", "4", "*", "2"]))
# ['3', '4', '2', '*', '+']
print(infix_to_postfix(["(", "3", "+", "4", ")", "*", "2"]))
# ['3', '4', '+', '2', '*']The output of the second call is exactly the token list you passed to eval_postfix earlier, which returns 14.0.
Common errors
The >= comparison makes operators of equal precedence left-associative. With 8 - 3 - 2, the first - is popped before the second is pushed, giving 8 3 - 2 -, which is (8 - 3) - 2. Using > would give 8 3 2 - -, which is 8 - (3 - 2) and wrong.
Other mistakes to watch for:
- Forgetting the
stack[-1] != "("check, which lets an operator pop a parenthesis into the output. - Skipping the final unmatched
(check, which lets(3 + 4pass silently. - Passing a string like
"3+4"instead of tokens. Split the input into tokens first, since numbers can have several digits.
Cost
Each token is pushed at most once and popped at most once, so the conversion runs in O(n) time. The stack holds at most n operators, so extra space is O(n).
Exercise
Convert 8 - 3 - 2 to postfix by hand using the algorithm. Why does the first - leave the stack before the second - is pushed?
Show answer
The result is 8 3 - 2 -. When the second - arrives, the stack top is the first - with equal precedence. The rule pops operators with equal or higher precedence, so the first - goes to the output. This makes subtraction left-associative, so the expression means (8 - 3) - 2 = 3.