A different Order of Operations

The Following is in Reverse Polish Notation (Sometimes called Postfix Notation)

5 6 2 + 6 1 4 2 - 8 + * - / 3 - +

What value does it evaluate to?


The answer is 0.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

Oliver Papillo
May 17, 2017

Using a stack, and showing all changes -

Input Stack
5 5 5 5
6 6 6 , 5 6, 5
2 2 2 , 6 , 5 2, 6, 5
+ + 8 , 5 8, 5
6 6 6 , 8 , 5 6, 8, 5
1 1 1 , 6 , 8 , 5 1, 6, 8, 5
4 4 4 , 1 , 6 , 8 , 5 4, 1, 6, 8, 5
2 2 2 , 4 , 1 , 6 , 8 , 5 2, 4, 1, 6, 8, 5
- 2 , 1 , 6 , 8 , 5 2, 1, 6, 8, 5
8 8 8 , 2 , 1 , 6 , 8 , 5 8, 2, 1, 6, 8, 5
+ + 10 , 1 , 6 , 8 , 5 10, 1, 6, 8, 5
* 10 , 6 , 8 , 5 10, 6, 8, 5
- 4 , 8 , 5 -4, 8, 5
/ / 2 , 5 -2, 5
3 3 3 , 2 , 5 3, -2, 5
- 5 , 5 -5, 5
+ + 0 0

So the answer is 0 0

I got 0 for the answer. Python agrees with me as well. The reason why your solution is incorrect is because you are subtracting and dividing the wrong way round in the stacks. Because of their non-commutative properties, you are getting an incorrect answer.


EDIT: Okay, so you fixed your solution. It's alright now. :)

Sharky Kesa - 4 years ago
Sharky Kesa
May 28, 2017

The answer is 0. I have a Python code and as well as a method to do it manually.

Operation Stack 5 5 6 6 5 2 2 6 5 + 8 5 6 6 8 5 1 1 6 8 5 4 4 1 6 8 5 2 2 4 1 6 8 5 2 1 6 8 5 8 8 2 1 6 8 5 + 10 1 6 8 5 10 6 8 5 4 8 5 / 2 5 3 3 2 5 5 5 + 0 \begin{array}{|c|c|} \hline \text{Operation} & \text{Stack}\\ \hline 5 & 5\\ \hline 6 & 6 \, 5 \\ \hline 2 & 2 \, 6 \, 5\\ \hline + & 8 \, 5\\ \hline 6 & 6 \, 8 \, 5\\ \hline 1 & 1 \, 6 \, 8 \, 5\\ \hline 4 & 4 \, 1 \, 6 \, 8 \, 5\\ \hline 2 & 2 \, 4 \, 1 \, 6 \, 8 \, 5\\ \hline - & 2 \, 1 \, 6 \, 8 \, 5\\ \hline 8 & 8 \, 2 \, 1 \, 6 \, 8 \, 5\\ \hline + & 10 \, 1 \, 6 \, 8 \, 5\\ \hline * & 10 \, 6 \, 8 \, 5\\ \hline - & -4 \, 8 \, 5\\ \hline / & -2 \, 5\\ \hline 3 & 3 \, -2 \, 5\\ \hline - & -5 \, 5\\ \hline + & 0\\ \hline \end{array}

Thus, the answer is 0. My Python code is below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def parse_rpn(expression):
    stack = []
    for val in expression.split(' '):
        if val in ['-', '+', '*', '/']:
            op1 = stack.pop()
            op2 = stack.pop()
            if val=='-': result = op2 - op1
            if val=='+': result = op2 + op1
            if val=='*': result = op2 * op1
            if val=='/': result = op2 / op1
            stack.append(result)
        else:
            stack.append(float(val))
    return stack.pop()

expression1 = '5 6 2 + 6 1 4 2 - 8 + * - / 3 - +'
print(parse_rpn(expression1))

This outputs an answer of 0.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...