Learning Scientific Programming with Python (2nd edition)
P4.2.3: A reverse polish notation calculator
Question P4.2.3
Reverse Polish Notation (RPN) (or postfix notation) is a notation for mathematical expressions in which each operator follows all of its operands (in contrast to the more familiar infix notation, in which the operator appears between the operands it acts on). For example, the infix expression 5 + 6
is written in RPN as 5 6 +
. The advantage of this approach is that parentheses are not necessary: to evaluate (3+7) / 2
, it may be written as 3 7 + 2 /
. A RPN expression is evaluated left-to-right with the intermediate values pushed onto a stack – a last-in, first-out list of values – and retrieved (popped) from the stack when needed by an operator. Thus the expression 3 7 + 2 /
proceeds with 3
and then 7
pushed to the stack (with 7 on top). The next token is +
, so the values are retrieved, added, and the result, 10
pushed onto the (now empty) stack. Next, 2
is pushed to the stack. The final token /
pops the two values, 10
and 2
from the stack, and divides them to give the result, 5
.
Write a program to evaluate a RPN expression consisting of space-delimited tokens (the operators +
-
*
/
**
and numbers).
Hints: Parse the expression into a list of string tokens and iterate over it, converting and pushing the numbers to the stack (which may be implemented by appending to a list
). Define functions to carry out the operations by retrieving values from the stack with pop
. Note that Python does not provide a switch...case
syntax, but these function objects can be the values in a dictionary with the operator tokens as the keys.