#判断运算符的优先级 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