# -*- coding: utf-8 -*-frompythonds.basic.stackimportStack# 中缀转后缀definfixToPostfix(infixexpr):prec={}prec["*"]=3prec["/"]=3prec["+"]=2prec["-"]=2prec["("]=1opStack=Stack()postfixList=[]tokenList=infixexpr.split()fortokenintokenList:iftokenin"ABCDEFGHIJKLMNOPQRSTUVWXYZ"ortokenin"0123456789":postfixList.append(token)eliftoken=='(':opStack.push(token)eliftoken==')':topToken=opStack.pop()whiletopToken!='(':postfixList.append(topToken)topToken=opStack.pop()else:while(notopStack.isEmpty())and \
(prec[opStack.peek()]>=prec[token]):postfixList.append(opStack.pop())opStack.push(token)whilenotopStack.isEmpty():postfixList.append(opStack.pop())return" ".join(postfixList)print(infixToPostfix("A * B + C * D"))print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )"))# 后缀计算defpostfixEval(postfixExpr):operandStack=Stack()tokenList=postfixExpr.split()fortokenintokenList:iftokenin"0123456789":operandStack.push(int(token))else:operand2=operandStack.pop()operand1=operandStack.pop()result=doMath(token,operand1,operand2)operandStack.push(result)returnoperandStack.pop()defdoMath(op,op1,op2):ifop=="*":returnop1*op2elifop=="/":returnop1/op2elifop=="+":returnop1+op2else:returnop1-op2print(postfixEval('7 8 + 3 2 + /'))# 中缀转前缀defopOrder(op1,op2):# 当新元素是),或者stack里的元素优先度高prec={}prec["*"]=3prec["/"]=3prec["+"]=2prec["-"]=2ifop1=='('orop2=='(':returnFalseelifop2==')':# 此时需要把)之前的符号pop出来returnTrueelse:ifprec[op1]<prec[op2]:returnFalseelse:returnTrue# )之前的较高优先度的符号pop出来definfixToPrefix(string):string=string.split()prefix=''stack=[]string_tmp=''forsinstring[::-1]:ifs=='(':string_tmp+=')'elifs==')':string_tmp+='('else:string_tmp+=s# reverse stringforsinstring_tmp:ifs.isalpha():prefix=s+prefix# 往前加else:whilelen(stack)andopOrder(stack[-1],s):# stack里有元素,且优先度较高,则加入prefix之前op=stack.pop()prefix=op+prefixiflen(stack)==0ors!=')':# 只要不是)的符号都往里加stack.append(s)else:# 如果stack有元素(,且s为),popstack.pop()iflen(stack):prefix=''.join(stack)+prefixreturn" ".join(prefix)print(infixToPrefix("A * B + C * D"))print(infixToPrefix("( A + B ) * C - ( D - E ) * ( F + G )"))print(infixToPrefix("( A + B ) * C - ( D - E ) * ( F + G ) - H * I"))print(infixToPrefix("( A + B ) * ( C + D + D )"))print(infixToPrefix("A + B + C + D"))print(infixToPrefix("A + B + C * D"))# 前缀计算defprefixEval(prefixExpr):operandStack=Stack()tokenList=(prefixExpr.split())[::-1]fortokenintokenList:iftokenin"0123456789":operandStack.push(int(token))else:operand1=operandStack.pop()operand2=operandStack.pop()result=doMath(token,operand1,operand2)operandStack.push(result)returnoperandStack.pop()defdoMath(op,op1,op2):ifop=="*":returnop1*op2elifop=="/":returnop1/op2elifop=="+":returnop1+op2else:returnop1-op2print(prefixEval('- * + 1 2 - 8 5 6'))