Practicing Polish/Prefix notation

944 Views Asked by At
 - * / 15 - 7 + 1 1 3 + 2 + 1 1 =
 - * / 15 - 7   2   3 + 2 + 1 1 =
 - * / 15     5     3 + 2 + 1 1 =
 - *        3       3 + 2 + 1 1 =
 -          9         + 2 + 1 1 =
 -          9         + 2   2   =
 -          9         4         =
                5

I need some guidance. I am trying to approach polish notation. From what I can see here right now is whenever we see two operators together, we could apply the operand recently aforementioned to the two operators right away. This is what I am having in mind. So from above,

 - * / 15 - 7 + 1 1 3 + 2 + 1 1 =
 - * / 15 - 7   2   3 + 2 + 1 1 =

So + 1 1 = 2, - 7 2 = 5

 - * / 15     5     3 + 2 + 1 1 =
 - *        3       3 + 2 + 1 1 =
 -          9         + 2 + 1 1 =

So / 15 5 = 3, * 3 3 = 9, 

I just want to be really sure here. Is it safe to assume this procedure?:

  1. starting from the left side of the prefix equation, read the next character one by one.
  2. if there are two characters that are operands sequentially, we apply the preceding operator right away.
  3. Replace the operation just now with its result. (So + 1 1 becomes 2). Go back to step 2 if there are more possible operation.

Note: Could somebody with higher reputation tag this question for "polish notation", please?

3

There are 3 best solutions below

0
On BEST ANSWER

Yes, your procedure is correct. It eliminates the need for parentheses altogether.

Another way to thinking about it is to go the other direction from right to left. The procedure is to, whenever you come to an operator, -always- apply it to two operands you currently have, replacing the 3 items (operator and two operands) with the value of the operation.

This latter procedure is called Reverse Polish Notation (RPN). It is a good method for computer implementation because all you need is a stack to remember any intermediate computations.

0
On

The above procedure looks correct. Essentially you work from left to right.

0
On

As Mitch and PEV pointed out the procedure does work. The reason it works comes as that the four arithmetical function +, -, *, and / all come as binary functions. They take two numbers and return one and only number. The principle underlying Polish notation comes as that binary functions take the two objects immediately succeeding the function symbol. The simplest expressions have to get parsed before more complicated expressions. So, first come numerical symbols. Then, if we only have the four binary arithmetical functions, come 3 character strings, and on up to more complicated expressions.