Loading...
Reverse Polish notation places an operator after its operands. It can encode an expression without brackets when operator arity and evaluation rules are known.
What you'll be able to do
Infix writes an operator between operands, such as (a+b)×c. RPN, also called postfix notation, writes the corresponding expression as a b + c ×. The position of each operator specifies when the preceding operand results are combined.
Conversion must preserve grouping and precedence. a+b×c becomes a b c × +, while (a+b)×c becomes a b + c ×. Simply moving every operator to the end loses the expression’s structure. An expression tree’s post-order traversal naturally generates postfix form.
Scan tokens from left to right. Push an operand. For a binary operator, pop the right operand first and the left operand second, calculate left operator right and push the result. After a valid complete expression, exactly one result remains.
For commutative operations an order mistake can be hidden. Subtraction and division expose it: the tokens 9 3 - mean 9-3, not 3-9. An operator with too few available operands indicates malformed input; several final values indicate an incomplete expression under the binary-operator model.
A stack-based interpreter can evaluate postfix code without repeatedly resolving brackets or infix precedence. The expression is still unambiguous only when tokenisation and the number of operands required by each operator are known. A multi-digit number must be one token, not several separate digits.
For an examination trace, show the stack after each token and identify its top end. When converting back to infix, pop expression strings in the same operand order and add grouping where needed. This makes the original dependency structure visible rather than merely reproducing numerical output.
| Token | Stack, bottom → top |
|---|---|
| 8 | 8 |
| 2 | 8, 2 |
| - | 6 |
| 3 | 6, 3 |
| * | 18 |
Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.