Infix to Postfix and unary/binary operators

Deadly 提交于 2019-12-19 04:16:09

问题


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:

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 ...?


回答1:


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.

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.

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'.

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.




回答2:


may be this chaotic C# code will help you. 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. 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. here '#' and '~' are used to depict the unary plus and unary minus in postfix expression(PFE).

you can handle all cases like 1+-1,1+(-1),1---1,1+--1 by using this approch.

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;       
        }       
    }
}


来源:https://stackoverflow.com/questions/2431863/infix-to-postfix-and-unary-binary-operators

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!