题目
将中缀表达式"3+(67-2)+23"转化成后缀表达式
思路
1.遇到操作数,直接输出;
2.栈为空时,遇到运算符,入栈;
3.遇到左括号,将其入栈;
4.遇到右括号,执行出栈操作,并将出栈的元素输出,直到弹出栈的是左括号,左括号不输出;
5.遇到运算符+ - * /时,弹出所有优先级大于或等于该运算符的栈顶元素,然后将该运算符入栈;
6.如果运算符优先级大于栈顶元素就直接将该运算符入栈;
7.最终将栈中没有弹出的元素依次出栈,输出。
代码区
expression1 = "3+(6*7-2)+2*3"
dic = {'+': 1, '-': 1, '*': 2, '/': 2, '(': 0, ')': 0} # 操作符优先级
def middle2behind(expresssion):
result = [] # 结果列表
stack = [] # 栈
for item in expresssion:
if item.isnumeric(): # 如果当前字符为数字那么直接放入结果列表
result.append(item)
else: # 如果当前字符为一切其他操作符
if len(stack) == 0: # 如果栈空,直接入栈
stack.append(item)
elif item in '(': # 如果当前字符为(,直接入栈
stack.append(item)
elif item == ')': # 如果右括号则全部弹出(碰到左括号停止)
t = stack.pop()
while t != '(':
result.append(t)
t = stack.pop()
# 如果优先级小于等于栈顶元素就将栈顶元素出栈,直到大于栈顶元素为止后自己入栈
elif dic[item] <= dic[stack[len(stack) - 1]]:
t = stack.pop()
# 循环直到全部符合条件的都弹出,直到遇到左括号
while dic[item] <= dic[t] and t != '(':
result.append(t)
if len(stack) > 0: # 防止出现空栈的pop发生错误
t = stack.pop()
else:
break
if t == '(': # 将刚才不小心弹出的(加回去
stack.append('(')
stack.append(item)
else: # 如果优先级大于栈顶元素就入栈
stack.append(item)
# 表达式遍历完了,但是栈中还有操作符不满足弹出条件,把栈中的东西全部弹出
while stack:
result.append(stack.pop())
# 返回字符串
return "".join(result)
print(middle2behind(expression1))
结果截图
新手上路,有错请指正;