简体   繁体   English

用一元/二元运算符将后缀固定

[英]Postfix to infix with unary/binary operators

I am trying to make a converter from postfix to infix notation and need some help. 我正在尝试将转换器从后缀转换为中缀符号,并且需要一些帮助。 There is already a question about infix-to-postfix conversion , which gives an example I am failing to convert back. 关于从infix到postfix的转换已经存在一个问题 ,它给出了一个我无法转换回去的示例。 (Note: a minus sign is missing there!) (注意:此处缺少减号!)

The following is the output of my converter, where the 1st "column" is postfix input, the 2nd is my infix output, and the 3rd is what I probably should get(?): 以下是我的转换器的输出,其中第一个“列”是后缀输入,第二个是我的中缀输出,第三个是我可能应该得到的(?):

2 -                      =   - 2                           =?    - 2                       true
1 + 2 +                  =   + 1 + 2                       =?    + 1 + 2                   true
1 + 2 + +                =   + (+ 1 + 2)                   =?    + 1 + + 2                 false
1 + 2 + + 3 - - 4 - -    =   - (- (+ (+ 1 + 2) - 3) - 4)   =?    + 1 + + 2 - - 3 - - 4     false

Do you think that it is possible to solve this problem, or the last two lines are actually converted correctly? 您是否认为有可能解决此问题,或者最后两行实际上已正确转换? How would you write algorithm to solve this problem? 您将如何编写算法来解决此问题?

Please, assume that more operators (not only + and - ) can be set as both unary and binary, where unary operators have higher precedence than binary ones. 请假定可以将更多运算符(不仅+- )设置为一元和二进制,其中一元运算符的优先级高于二元运算符。

References 参考文献

  1. Ruby Quiz #148: Postfix to Infix , also via Google Groups Ruby Quiz#148:Infix的Postfix ,也通过Google网上论坛
  2. Shunting-yard algorithm (C, Python, Perl) with unary operator support on LiteratePrograms 在LiteratePrograms上具有一元运算符支持的调车场算法(C,Python,Perl)

Postfix notation does not have the concept of precedence, as the operands for any operator are always the top N values on the stack (which are then replaced by the result of the operator. 后缀表示法没有优先级的概念,因为任何运算符的操作数始终是堆栈中的前N个值(然后将其替换为运算符的结果。

One problem with postfix notation is that it does not cope well with operator symbols that can refer to different operators depending on the number of operands (such as -, which can denote either unary or binary minus). 后缀表示法的一个问题是,它不能很好地应付根据操作数的数量可以引用不同运算符的运算符(例如-,可以表示一进制或二进制减号)。 The only way out of that is to ensure each operator has a unique symbol representing it. 唯一的解决方法是确保每个操作员都有一个代表它的唯一符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM