A-level Computing/AQA/Paper 1/Fundamentals of algorithms/Reverse polish





Reverse polish notation (otherwise known as post-fix, RPN for short) is a way of representing mathematical expressions. The notation is used because the format that the expression is in is easier for machines to interpret rather than the notation we are used to, infix notation, where the operator is in between the numbers. The equation can be complex or simple. RPN doesn't require brackets as the equations are laid out in such a format that they aren't required for machines to understand.

There is no inherent reason why operators should be written between the operands, as they are with the standard arithmetic operators. The operators could come before the operands (prefix), between (infix), or after (postfix). Here is the same expression written in three formats:

We are used to seeing arithmetic written infix and functions written in prefix notation, often with brackets (e.g.  to express the operation of taking a square root). We could write arithmetic in the same form, such as using Python's  library:

Advantages of postfix notation
Neither prefix nor postfix notation require brackets to express grouping of operations: the order of evaluation is dictated solely by the order of operations.

Infix notation can only easily express operations that take one or two parameters (such as binary addition or square roots). Operations that take more than two parameters require typographic embellishments such as brackets.

Some programming languages, called stack-based programming languages, use the model of stack-based evaluation throughout. The most well-known stack-based languages are PostScript and Forth.

Evaluation of Reverse Polish expressions
Expressions stated in reverse Polish notation can be simply evaluated using a stack. As the expression is read, values are pushed onto the stack. When an operation is read, values are popped from the stack and the result pushed back on the stack. The result left on the stack is the overall value of the expression.

The use of a stack and uniform precedence rules makes it very easy to write code to calculate the results of reverse polish expressions.



Example
Using a slightly more complex example than above, evaluation of "3 4 × 10 2 ÷ +" can proceed as follows:

The result left on the stack, 17, is the overall value of the expression.

YouTube Video Example
A video example can be seen here from Computerphile on Youtube: https://www.youtube.com/watch?v=7ha78yWRDlE