1

I have tried numerous times to solve the following using the shunting yard algorithm: 1*2-3/4+5*6-7*8+9/10

Infix Notation:

"1*2-3/4+5*6-7*8+9/10"

Postfix Notation:

[1,2,*,3,4,/,5,6,*,7,8,*,9,10,/,+,-,+,-]

The correct answer is -24.

Every time I solve the postfix notation version of this I get 28.

I have yet to find a working RPN calculator online ... So I have turned to stack overflow.

Nate Eldredge
  • 48,811
  • 6
  • 54
  • 82
Some Guy
  • 11
  • 1
  • First of all, are you aware that your postfix notation translates back to `1*2-(3/4+5/6-(7*8+9/10))`? Which is clearly not what you want. – Nate Eldredge May 24 '21 at 01:57
  • As a simpler example, try applying the algorithm to `1-2+3`. Make sure you get `[1,2,-,3,+]`. The erroneous logic you're applying sounds like it would give you `[1,2,3,+,-]`. If you can't see where you're going wrong, write out a step-by-step explanation of your logic, and edit your question to include it. – Nate Eldredge May 24 '21 at 02:03
  • Following the version of the algorithm at https://en.wikipedia.org/wiki/Shunting-yard_algorithm, I get postfix that starts out `[1,2,*,3,4,/,-,...]`. When you process the first `+`, you have `-,/` on the operator stack. You pop `/` because it has higher precedence than `+`. You also pop `-` because it has the same precedence as `+` and is left associative. I think this last part is what you may be missing. – Nate Eldredge May 24 '21 at 02:16
  • This is an old question, but I just wonder why you say the correct answer should be -24. It's clearly a sum of integers EXCEPT for 3/4 and 9/10 whose decimal parts do not "cancel out", so IMHO the result can by no means be an integer. – Philipp Imhof Feb 25 '23 at 12:50
  • 1
    @PhilippImhof: I assumed that `/` is doing truncating integer division, so `3/4` and `9/10` are both 0. – Nate Eldredge Feb 25 '23 at 17:17

1 Answers1

1

I am working on my own Shunting Yard algorithm, and so this might not be 100% correct, but I what Im getting is [ 1, 2, *, 3, 4, /, -, 5, 6, *, +, 7, 8, *, -, 9, 10, /, +] The Wikipedia for Shunting Yard Algorithm gives the pseudo code for this parsing, and I dont think I could explain it better. As some alredy said, you might want to look into how precedence and associativity affect parsing.