1

I'm having a homework: When we input the math expression like -(2 + 3) * 1/5 , the output should be -1. After doing some research, I found that RPN algorithm is the way to solve this problem. So what I did is convert the expression from infix to postfix. But the problem is I can't determine the operands in some situations, like this:

Input: 11+((10-2)*6)+7
Infix-to-Postfix-----------
Output: 11102-6*+7+  

There is no white space between "11" and "10", and between "10" and "2" so I can't determine every single operand correctly . Because my output (postfix) is a string, I'm totally don't know how to solve this problem. Is there any idea for this?

TamTam
  • 547
  • 1
  • 5
  • 16
  • 1
    It's *a* way to solve this problem. There are *lots* of ideas for this; expression parsing is a well-known problem with many examples and tutorials. Please see the [How to Ask](https://stackoverflow.com/help/how-to-ask) page: non-working code should be presented. – Dave Newton Sep 10 '19 at 12:26
  • 2
    And you do not want a concatenation of tokens but rather a `List` of tokens. And one needs to differ from minus operator with one or two arguments. – Joop Eggen Sep 10 '19 at 12:35
  • To push a value(digits), use a comma operator, so that you have 11,10,2-6*+7+ – Adder Sep 10 '19 at 12:44
  • Thanks for the advices, I'm trying my best! – TamTam Sep 10 '19 at 12:53

1 Answers1

1

You described the problem -- and obvious solution -- in your posting: the postfix output you chose destroys critical information from the original expression. The obvious solution is that you have to change your postfix routine to preserve that information.

The particular problem is that you can no longer parse a string of digits into the original integers. The obvious solution is to retain or insert a unique separator. When you emit (output) an integer, add some sort of punctuation. Since RPN uses only numbers and a handful of operators, choose something easy for you to detect and to read yourself: a space, comma, or anything else that would work for you.

For instance, if you use a simple space, then you'd have RPN format as

11 10 2 -6 *+7 +

When you read this in your RPN evaluator, use the separator as a "push integer" signal (or operator).

Note that I have used this separator as a terminal character on every integer, not merely a separator between consecutive integers. Making it a terminal simplifies both output processing and input parsing. Deciding whether or not to add that symbol depends on only one token (the integer), rather than making it conditional upon two adjacent tokens (requiring a small amount of context status).

Prune
  • 76,765
  • 14
  • 60
  • 81