CSC212 Homework 4 2014
--D. Thiebaut (talk) 15:49, 1 October 2014 (EDT)
Problem #1
Write a program that computes the result of an arithmetic expression written in reverse polish notation (RPN), also called postfix notation because the operator appears after (post) the operands. You may want to read this page introducing the concept.
A regular, error-free, arithmetic expression can be transformed into its RPN easily, as illustrated with a few examples:
regular expression | RPN expression |
---|---|
3 + 5 |
3 5 + |
3 * ( 5 - 2 ) |
3 5 2 - * |
(4 -1 ) * 8 |
4 1 - 8 * |
( 5 * 10 ) / ( 3 - 2 ) |
5 10 * 3 2 - / |
RPN expressions can be solved very easily by using a stack. For example, if the expression is:
3 5 + 7 *
which corresponds to (3 + 5) * 7, we proceed as follows: we read the symbols (numbers and operators) one at a time from the input, and if we find a number, we push it in the stack. If we find an operator, we pop 2 numbers from the stack, one after the other, apply the operator to the two numbers, then push the result back in the stack.
- Example
- Assume we want to evaluate the postfix string "3 5 + 6 *". Its infix equivalent to (3 + 5 ) * 6, which is 48.
Here we go: we scan our string, and get each number an operator one at a time.
3 --> push it in the stack: stack = [3] 5 --> push it in the stack: stack = [5 3] (the top of the stack is 5) + --> Operator! we pop the stack, get 5, pop again, get 3, add 5+3 together, 8, push that back in the stack. stack = [8] 6 --> push it in the stack: stack = [6 8] * --> Operator! we pop the stack, get 6, pop again, get 8, multiply 6 by 8 ,48, push that back in the stack. stack = [48] Done! the result is at the top of the stack.