Conversion and calculation of infix expressions and suffix expressions, python and data structure [1], Stack/stack[1]--

Source: Internet
Author: User

Conversion and calculation of infix expression and suffix expression

Directory

    1. infix expression converted to suffix expression
    2. Calculation of postfix expressions

1 infix expression converted to suffix expression

The infix expression is converted to a suffix expression in the following way:

    1. Gets the element of the infix expression in turn,
    2. If the element is an operand (number/letter, etc.), the suffix expression is added
    3. If the element is an operator, it is pressed into the stack, when compared to the stack operator and the stack of the elements of the calculation level, the level is greater than or equal to the stack element of the stack inside the operator will be pop-up stack, added to the suffix expression
    4. The left parenthesis directly into the stack, the highest priority, do not eject the stack elements
    5. The closing parenthesis is not in the Stack, but pops all the elements into the suffix expression until the matching opening parenthesis is met, and the opening parenthesis is popped but not added to the suffix expression
    6. After the elements of the prefix expression are exhausted, the elements in the stack are popped into the suffix expression.

The code implementation process is as follows,

Full code

1  fromLinked_list_stackImportStack2 3Sign = {'+': 1,'-': 1,'*': 2,'/': 2,'(': 3}4 5 6 defInfix_to_postfix (expr):7     Global Sign8out = []9s =Stack ()Ten      forIinchExpr: One         ifIinchSign.keys (): A             #Pop All-level sign except left bracket -              whiles.top (): -                 ifSign[s.top ()] < Sign[i]orS.top () = ='(': the                      Break - Out.append (S.pop ()) -             #Push Sign - S.push (i) +         elifi = =')': -             #Pop all sign until left bracket encountered +              whileS.top ()! ='(': A Out.append (S.pop ()) at             #Pop Left Bracket - S.pop () -         Else: -             #Push Number - out.append (i) -  in      whiles.top (): - Out.append (S.pop ()) to     return out +  -  the if __name__=='__main__': *EP ='A + b * C + (d * e + f) * g' $     Print(' '. Join (Infix_to_postfix (Ep.split (' '))))
View Code

Segmented interpretation

First, import the Stack class from the list stack and define the precedence of each operator

1  from Import Stack 2 3 sign = {'+'-'*'  '/'(': 3}

Then define the conversion function,

    1. The function takes an iterative object of an infix expression, creates a list of out-holding suffix expressions, and an empty stack s
    2. The infix expression is then traversed to determine the type of the traversal element, and if the operand is added out,
    3. If the closing parenthesis is followed by a pop-up stack, the inside element is added to the out list until the opening parenthesis is met, and the opening parenthesis is not added.
    4. If the normal operator is pressed into the stack, and compares the operator precedence in the stack, and then pops up a high-priority or the same priority operator,
    5. At the end of the traversal, the inside of the stack pops up and returns the string form of the suffix expression.
1 defInfix_to_postfix (expr):2     Global Sign3out = []4s =Stack ()5      forIinchExpr:6         ifIinchSign.keys ():7             #Pop All-level sign except left bracket8              whiles.top ():9                 ifSign[s.top ()] < Sign[i]orS.top () = ='(':Ten                      Break One Out.append (S.pop ()) A             #Push Sign - S.push (i) -         elifi = =')': the             #Pop all sign until left bracket encountered -              whileS.top ()! ='(': - Out.append (S.pop ()) -             #Pop Left Bracket + S.pop () -         Else: +             #Push Number A out.append (i) at  -      whiles.top (): - Out.append (S.pop ()) -     return out -  -  in if __name__=='__main__': -EP ='A + b * C + (d * e + f) * g' to     Print(' '. Join (Infix_to_postfix (Ep.split (' '))))

Finally, you can get an expression that outputs the result of

A b c * + D e * f + G * +

2 calculation of the suffix expression

The calculation of Postfix expressions is also a process of converting suffixes to infix:

    1. First, the suffix expression is traversed in turn,
    2. When the element is the operand, it is pressed into the stack,
    3. When the element is an operator, the top two elements in the stack are popped, and the resulting results are pressed into the stack again,
    4. Until the end of the suffix expression traversal, there is only one element in the stack that is the result of the final operation, and the pop-up stack

The implementation of the process is very simple, the specific code is as follows, where infix expression to the suffix expression method is the method defined previously

Full code

1  fromLinked_list_stackImportStack2   3Sign = {'+': 1,'-': 1,'*': 2,'/': 2,'(': 3}  4   5   6 defPostfix_calc (expr):7     Global Sign8s =Stack ()9      forIinchExpr:Ten         ifIinchSign.keys (): Oneright =Str (s.pop ()) Aleft =Str (s.pop ()) -Cal =' '. Join (left, I, right) -             #cal = '. Join ([Str (S.pop ()), I, str (s.pop ())][::-1]) the S.push (eval (CAL)) -         Else:   - S.push (i) -     returnS.pop () +    - if __name__=='__main__':   +EP ='((2 + 3) * 8 + 5 + 3) * 6'   A     Print(eval (EP)) at     Print(Postfix_calc (Infix_to_postfix (Ep.split (' '))))   -    -EP ='3 + (2 * 9)/2 * (3 + 6) * 7'   -     Print(eval (EP)) -     Print(Postfix_calc (Infix_to_postfix (Ep.split (' '))))

Finally, the results of the calculation of infix expressions and infix suffixes are calculated and the results are the same.

288288570.0570.0

Conversion and calculation of infix expressions and suffix expressions, python and data structure [1], Stack/stack[1]--

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.