def infixToPostfix(infixexpr): opstack = Stack() # 创建空栈 result = [] # 结果的列表 prec = {'*': 3, '/': 3, '+': 2, '-': 2, '(': 1} # 运算符的优先级 operator_list = ['+', '-', '*', '/'] for token in tolist(infixexpr): if token.capitalize() in string.ascii_uppercase: # 判断是否是操作数 result.append(token.capitalize()) else: if token == '(': # 判断是是否是左括号 opstack.push(token) elif token == ')': # 判断是否是右括号 topToken = opstack.pop() while topToken != '(': result.append(topToken) topToken = opstack.pop() elif token in operator_list: # 判断是否是运算符 while not opstack.isEmpty() and (prec[opstack.peek()] >= prec[token]): result.append(opstack.pop()) opstack.push(token) else: pass while not opstack.isEmpty(): result.append(opstack.pop()) return "".join(result)
def infixToPostfix(infixexpr): # 记录操作符优先级 prec = {} prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 # 初始化栈 opStack = Stack() postfixList = [] # 将表达式转为单词列表 tokenList = infixexpr.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList)