简体   繁体   English

中缀到Postfix和一元/二元运算符

[英]Infix to Postfix and unary/binary operators

I have a piece of code that converts an infix expression to an expression tree in memory. 我有一段代码将中缀表达式转换为内存中的表达式树。 This works just fine. 这很好用。 There's just one small trouble. 只有一个小问题。 I just connect work out how to involve the unary operators correctly (the right associative ones). 我只是想弄清楚如何正确地使用一元运算符(正确的关联运算符)。

With the following infix expression : 使用以下中缀表达式:

+1 + +2 - -3 - -4

I would expect an RPN of: 我希望RPN为:

1+2++3-4--

Yet, none of the online infix-post converters I can find handle this example in the way I would expect. 然而,我能找到的在线中缀后转换器都没有像我期望的那样处理这个例子。 Does anyone have a clear explanation of handling right associative operators, specifically the binary ones that can be mistaken for the unary ones? 有没有人对处理右关联运算符有明确的解释,特别是那些可以被误认为是一元运算符的二元运算符?

Edit/Clarification: I would like to know how to deal with the unary operators during the translation from infix to postfix. 编辑/澄清:我想知道如何在从中缀到后缀的翻译过程中处理一元运算符。 Ie: recognizing the same '-' character for example as being unary instead of binary operator and thus a different precedence. 即:识别相同的' - '字符,例如是一元而不是二元运算符,因此具有不同的优先级。 I would think of using a state machine perhaps with two states but ...? 我会想到使用状态机可能有两个状态但是......?

Well, you need to determine if a given operator is binary/unary during the parsing stage. 那么,您需要在解析阶段确定给定的运算符是否为二进制/一元。 Once you do that, when you create the RPN, you can tag the operators as taking 2 or 1 arguments. 一旦这样做,当您创建RPN时,您可以将运算符标记为采用2或1个参数。

You could try using the Shunting Yard algorithm to do the parsing (and creation of RPN at the same time), which was designed to work with unary operators too. 您可以尝试使用Shunting Yard算法进行解析(以及同时创建RPN),这也是为了与一元运算符一起工作。

In any case, if all you care about is unary + or -, you could just insert a 0 with brackets when you see a + or - that appears 'unexpectedly'. 在任何情况下,如果您关心的只是一元+或 - ,当您看到“意外”出现+或 - 时,您可以只插入带括号的0。

For instance 例如

+1 + +2 - -3 - -4

You should be able to make a pass through it and convert to 你应该能够通过它并转换为

(0+1) + (0+2) - (0-3) - (0-4)

Now you don't need to worry about the unary + or - and can probably forget about tagging the operators with the number of arguments they take. 现在你不需要担心一元+或 - 并且可能忘记用它们所采用的参数数量来标记运算符。

may be this chaotic C# code will help you. 可能是这个混乱的C#代码会帮助你。 a unary operator has the maximum priority in arithmetic operations, so the precedence will be higher for them. 一元运算符在算术运算中具有最大优先级,因此它们的优先级将更高。 for identifying unary operator I have taken a boolean variable unary which will be set true after each operator token and false after an operand. 为了识别一元运算符,我采用了一个布尔变量一元,它将在每个运算符标记后设置为true,在操作数之后设置为false。 You have to use a different notation for unary plus and minus operator so that you can distinguish between unary and binary operator in PFE. 您必须为一元加号和减号运算符使用不同的表示法,以便您可以区分PFE中的一元和二元运算符。 here '#' and '~' are used to depict the unary plus and unary minus in postfix expression(PFE). 这里'#'和'〜'用于描述后缀表达式(PFE)中的一元加和一元减。

you can handle all cases like 1+-1,1+(-1),1---1,1+--1 by using this approch. 你可以使用这个approch处理所有情况,如1 + -1,1 +( - 1),1 --- 1,1 + - 1。

using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DSA
{
    class Calculator
    {
        string PFE;
        public Calculator()
        {
            Console.WriteLine("Intializing Calculator");
        }

        public double Calculate(string expression)
        {
            ConvertToPost(expression);
            return CalculatePOST();
        }

        public void ConvertToPost(string expression)
        {
            expression = "(" + expression + ")";

            var temp = new DSA.Stack<char>();
            string ch = string.Empty;
            bool unary = true;
            char a;
            foreach (var b in expression)
            {
                a = b;
                if (!a.IsOperator()) {
                    ch += a.ToString();
                    unary = false;
                }
                else
                {
                    if (ch!=string.Empty) 
                    PFE += ch+",";
                    ch = string.Empty;
                    if(a!='(' && a!=')')
                    {
                        if (unary == true)
                        {
                            if (a == '-') a = '~'; else if (a == '+') a = '#'; else throw new InvalidOperationException("invalid input string");
                        }
                        try
                        {
                            if (a.Precedence() <= temp.Peek().Precedence())
                            {
                                PFE += temp.Pop().ToString() + ",";
                            }
                          }
                        catch(InvalidOperationException e)
                        {

                        }

                            temp.Push(a);
                            unary = true;
                    }
                    if (a == '(') { temp.Push(a);}
                    if(a==')')
                    {
                       for(char t=temp.Pop();t!='(';t=temp.Pop())
                        {
                            PFE += t.ToString() + ","; 
                        }
                    }
                }

            }

        }

        public double CalculatePOST()
        {
            var eval = new Stack<double>();
            string ch = string.Empty;
            bool skip = false;
            foreach(char c in PFE)
            {
                if(!c.IsOperator())
                {
                    if (c == ',')
                    {
                        if (skip == true)

                        {
                            skip = false;
                            continue;
                        }
                        eval.Push(Double.Parse(ch));
                        ch = string.Empty;
                    }
                    else ch += c;
                }
                else
                {
                    if (c == '~')
                    {
                        var op1 = eval.Pop();
                        eval.Push(-op1);
                    }
                    else if (c == '#') ;
                    else
                    {
                        var op2 = eval.Pop();
                        var op1 = eval.Pop();
                        eval.Push(Calc(op1, op2, c));
                    }
                    skip = true;
                }
              }
            return eval.Pop();
        }

        private double Calc(double op1, double op2, char c)
        {   
           switch(c)
            {

                case '+':
                    return op1 + op2;
                case '-':
                    return op1 - op2;
                case '*':
                    return op1 * op2;
                case '%':
                    return op1 % op2;
                case '/':
                    return op1 / op2;
                case '^':
                    return float.Parse(Math.Pow(op1,op2).ToString());
                default:
                    throw new InvalidOperationException();
            }
        }
    }


    public static class extension
    {
        public static bool IsOperator(this char a)
        {
            char[] op = {'+','-','/','*','(',')','^','!','%','~','#'};
             return op.Contains(a);
        }

        public static int Precedence(this char a)
        {
            if (a == '~' || a== '#')
                return 1;
            if (a == '^')
                return 0;
            if (a == '*' || a == '/' || a=='%')
                return -1;
            if (a == '+' || a == '-')
                return -2;
            return -3;       
        }       
    }
}

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

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