About infix expressions and inverse Polish expressions (final)

Source: Internet
Author: User

Inverse Polish expressions are widely used in compilation principles. However, when studying and calculating a one-dimensional equation, it is found that it is easier to calculate a one-dimensional equation using the inverse Polish algorithm, the reason is that the inverse polish expression has an incomparable advantage-split brackets (I will post the algorithm program for the one-dimensional equation later ).

 

The standard expression is like "A + B". In mathematics, it is called Infix Notation because the operator number is in the middle of two calculation objects. The Prefix Notation expression, for example, "+-A * B c d", is converted into an infix expression: "A-B * C + D "; postfix Notation. For example, the mentioned infix expression is converted into A suffix expression: "a B C *-D + ". To commemorate the Polish mathematician Jan Lukasiewicz, a prefix expression is called a Polish expression, and a suffix expression is called a Reverse Polish Notation ).

 

The advantage of the suffix expression is obvious. during processing, the compiler reads the inverse polish expression in the order from left to right. When an operation object is pushed into the stack, when an operator is encountered, the two objects extracted from the stack are computed. This process exactly conforms to the principle of computer computing.

 

A suffix expression is easier to convert than a prefix expression, and its leftmost aspect must be a number. In actual programming, it will realize its advantages.

 

A greater advantage of an inverse polish expression is the split of parentheses. After the infix expression is converted to an inverse polish expression based on the operator level, the operation order has replaced the operator level, this also avoids the special processing of parentheses to increase the operation level.

 

Now I will briefly introduce the standard algorithm for converting an infix expression to an inverse polish expression.

 

A) returns an infix expression 1*(2 + 3)

 

B) the system first defines two first-come stacks: operator number stack (inbound stack in) and suffix expression output symbol stack (outbound stack out)

 

C) The System reads the infix expression from left to right.

 

D) read the number and press it directly into the stack (out)

 

E) read the first operator and press it directly into the stack (in)

 

F) read "(" directly pushed into the stack (in). The data in the two stacks is: in 1; out *,(

 

E) Compare the second read operator "+" with the stack top operator "(") in the stack to directly go to the stack above the stack top level, if the value is lower than or equal to the top level of the stack, the inbound stack in (that is, the outbound stack) should be pushed to the outbound stack. For example, the current operation order of the inbound stack is (, *,/. If the operator to be read by the system is + and the level ratio is lower /, * is pushed out of the stack in sequence, and the/and * symbols are released in the stack. Finally, the results of in (; out/, * are obtained.

 

F) when reading ")", find the nearest sign in the stack (", press all the symbols in front of it into the stack in the first-in-out order, and decompress the package, "(" and ")" offset. The data in the two stacks is: in 1, 2, 3, +; out *

 

G) after the system reads the infix expression, all the symbols in the in stack are extracted in the order of forward and forward, and pushed to the out stack in sequence, the final output stack result should be 1, 2, 3, + ,*

 

H) decompress the out stack out in the first-in-first-out order to obtain the standard extension EXPRESSIONS 1, 2, 3, + ,*

 

Data of two stacks:

In

Out

 

1

*

1

*,(

1

*,(

1, 2

*, (, +

1, 2

*, (, +

1, 2, 3

*

1, 2, 3, +

 

1, 2, 3, + ,*

 

During the process of converting the infix expression to the inverse polish expression, note that "(" No matter why the level in the inbound Stack directly goes into the stack, when encountering ") "Find the last entry" (", and press all the symbols before" ("into the stack. I made a mistake in programming. I only judged by the operator level and the result showed an incorrect result.

 

The purpose of the inverse polish expression, the standard algorithm for converting the infix expression to the inverse polish expression, and the calculation method for the inverse polish expression are briefly outlined above. Next, I will show the operation level of each operator when the infix expression is converted to the inverse polish expression.

 

The operation level of the operator is the sequence of the equation operation, as follows:

Operator

Level

Space

0

)

1

(

2

+ ,-

3

*,/

4

Operation object

-1

 

I now provide C # source code for converting the infix expression to the inverse polish expression. The code runs through. net2005. Some codes are not optimized due to time reasons. If you are interested, please give me better suggestions.

Using system;
Using system. Collections. Generic;
Using system. text;
Using system. collections;

Namespace test {
/// <Summary>
/// Operator Structure
/// </Summary>
Public struct Operator
{

Public String operatorstack;
Public int Level;
Public Operator (string OperatorStack, int Level)
{
This. OperatorStack = OperatorStack;
This. Level = Level;
}
/// <Summary>
/// Operator operation level
/// </Summary>
/// <Param name = "strOperator"> operator </param>
/// <Returns> operation operator. If space is returned, 0 is returned. If an error is returned,-1 is returned. </returns>
Private int operatorlevel (string stroperator)
{
Switch (stroperator)
{
Case "+ ":
Return 3;
Case "-":
Goto case "+ ";
Case "*":
Return 4;
Case "/":
Goto case "*";
Case "(":
Return 2;
Case ")":
Return 1;
Case "":
Return 0;
Case "[":
Return-2;
Default:
Return-1;

}
}

/// <Summary>
/// Convert the infix expression to the inverse polish expression
/// </Summary>
/// <Param name = "ExprEssion "> standard infix expression </param>
/// <Returns> standard reverse polish expression </returns>
Public string RpnExprEssion (string ExprEssion)
{

Try
{
// Add the end tag?
String strexprEssion = exprEssion + "#";
// Define the stack and the inbound Stack
String [] strnum = exprEssion. Split (New char [] {'+ ','-','*','/','(',')'});
Int intnum = strnum. getlength (0 );
// Operator Stack
Stack lifecycle = new stack ();
// Define the output Stack
Stack output = new Stack ();
// Define prefix expression character read pointer
Int I = 0;
// Define the pointer to the number array currently read
Int n = 0;
// Define operation operator-level functions
Operator op = new Operator ();
// Size of the output Stack
Int intStackCount = 0;
// Read the prefix expression from left to right
While (I <strExprEssion. Length)
{
// Read one character
String strChar = strExprEssion. Substring (I, 1 );
If (strChar! = "#")
{

// Operation level of the character
Int intLevel = this. OperatorLevel (strChar );
If (intLevel = 0)
// Read the next character with Space
{
I ++;
}

Else if (intLevel =-1)
// Push numbers directly into the output Stack
{
For (int m = n; m <strNum. GetLength (0); m ++)
{
If (strNum [m]! = "")
{
// Move the array pointer
N = m + 1;
// Push the number directly into the stack
Output. Push (strNum [m]);
// Move the string to read the pointer
I = I + strNum [m]. Length;
Break;
}
}
}

Else // The Operation character is pushed to the operator stack at the arithmetic character level
{
If (bytes. Count = 0)
{
// The operator stack is empty and pushed directly to the stack.
Iterator. Push (new operator (strchar, intlevel ));
// Move the character read pointer
I ++;
}
Else
{
OP = (operator) operator. Peek ();
If (intLevel> op. Level | intLevel = 2)
{
// The Operation character is higher than the last level of the operator stack or the operator is '(' directly pushed into the operator Stack
Iterator. Push (new Operator (strChar, intLevel ));
// Move the character read pointer
I ++;
}
Else
{
// If the operation character is not higher than the last level of the operator stack, the operator stack is taken out of the stack until it is higher
IntStackCount = Summary. Count;
For (int m = 0; m <intStackCount; m ++)
{
Op = (Operator) Operator. Peek ();
If (op. Level> = intLevel)
{
// Extract the operator from the stack and press it into the input stack.
Output. Push (op. OperatorStack );
Int l = op. Level;
Metadata. Pop ();
If (l = 2)
{
// If the final operator in the operator stack is '(', stop the output stack.
I ++;
Break;
}
}
Else
{
// Until the operator is higher than the last level in the operator stack
Iterator. Push (new Operator (strChar, intLevel ));
I ++;
Break;
}
}
}
}
}
}
Else
{
// Read the end Of the prefix expression and press the operator Stack directly into the output stack.
IntStackCount = Summary. Count;
For (INT m = 0; m <intstackcount; m ++)
{
OP = (operator) operator. Peek ();
Output. Push (op. operatorstack );
Metadata. Pop ();
}
I ++;
}

}
// Form an output string with a reverse polish expression
Object [] strOutput = output. ToArray ();
String str = Convert. ToString (strOutput [strOutput. GetLength (0)-1]);
For (int m = strOutput. GetLength (0)-2; m> = 0; m --)
{
If (Convert. ToString (strOutput [m])! = "(" & Convert. ToString (strOutput [m])! = ")")
{
Str = str + "," + Convert. ToString (strOutput [m]);
}
}
Return str;
}

Catch
{
Throw;
}

}

/// <Summary>
/// Reverse polish expression
/// </Summary>
/// <Param name = "ExprEssion "> standard inverse polish expression </param>
/// <Returns> reverse polish expression </returns>

Public double ComplieRpnExp (string ExprEssion)
{

Try
{
// Split the reverse polish expression
String [] strNum = ExprEssion. Split (new char [] {','});
Int intLenth = strNum. GetLength (0 );
// Define a digital Stack
Stack number = new Stack ();
For (int I = 0; I <intLenth; I ++)
{
Int intLevel = this. OperatorLevel (strNum [I]);
If (intLevel =-1)
{
// Press the number Stack directly if it is a number
Number. Push (Convert. ToDouble (strNum [I]);

}
Else if (intLevel> 2)
{

// Extract and calculate the last two data in the digital stack, and press the calculation result into the stack.
If (number. Count> 1)
{

// Ensure that the digital Stack has more than two numbers
Double dLastin = Convert. ToDouble (number. Pop ());
Double dFirstin = Convert. ToDouble (number. Pop ());
Double dResult = this. ComplieRpnExp (dLastin, dFirstin, strNum [I]);
If (! Convert. IsDBNull (dResult ))
{
// Press the computation result
Number. Push (dResult );
}
}
}
}
Double d = Convert. ToDouble (number. Pop ());
Number. Clear ();
Return d;
}

Catch
{
Throw;
}
}

/// <Summary>
/// Calculate the inverse polish expression
/// </Summary>
/// <Param name = "dLastin"> the number that is finally pushed into the digital stack </param>
/// <Param name = "dFirstin"> the number first pushed into the digital stack </param>
/// <Param name = "regular"> operator </param>
/// <Returns> return the calculation result </returns>

Private double ComplieRpnExp (double dLastin, double dFirstin, string struct)
{

Switch)
{

Case "+ ":
Return dfirstin + dlastin;
Case "-":
Return dfirstin-dlastin;
Case "*":
Return dFirstin * dLastin;
Case "/":
Return dFirstin/dLastin;
Default:
Return 0;

}
}
}
}

Now all the reverse Polish expressions have been done. Now I can convert the infix expression into a reverse polish expression and then calculate it without worrying about the issue of parentheses.

 

The solutions for multiple and even multiple unary equations can be solved.

Source: http://www.xileju.biz/index.php/18/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.