[Python] infix expression-to-prefix expression

Source: Internet
Author: User

#判断运算符的优先级 def oporder(OP1,OP2):Order_dic = {' * ':4,' $ ':5,'/':4,' + ':3,'-':3}ifOP1 = =' (' orOP2 = =' (':return False    elifOP2 = =' ) ':return True    Else:ifORDER_DIC[OP1] < ORDER_DIC[OP2]:return False        Else:return True def infix2prefix(String):prefix ="'stack = [] string_tmp ="'     forSinchstring[::-1]:ifs = =' (': String_tmp + =' ) '        elifs = =' ) ': String_tmp + =' ('        Else: String_tmp + = s forSinchString_tmp:ifS.isalpha (): prefix = s + prefixElse: whileLen (Stack) andOporder (stack[-1],s): op = stack.pop () prefix = op + prefixifLen (stack) = =0 ors! =' ) ': Stack.append (s)Else: Stack.pop ()ifLen (stack): prefix ="'. Join (stack) + prefixreturnPrefixif__name__ = =' __main__ ': forStringinch[' A+b*c ',' (a+b) *c ',' ((A-(B+C)) *d $ (e+f) ']:PrintString' ==> ', Infix2prefix (String)

Output

>>> A+B*C ==> +A*BC(A+B)*C ==> *+ABC((A-(B+C))*D)$(E+F) ==> $*-A+BCD+EF

[Python] infix expression-to-prefix expression

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.