def is_op(c):
return c in "+-*/"
def get_pri(c):
assert is_op(c)
p = {
"+":1,
"-":1,
"/":2,
"*":2,
}
return p[c]
string = "1+(2*3)/2+3"
# 中缀表达式转后缀表达式
def convert(string):
output = ""
stack = []
for c in string:
# 如果是运算符
if is_op(c):
# 栈非空 && 上一个是操作符 && 优先级大于【等于】当前操作符
while stack and is_op(stack[-1]) and get_pri(stack[-1]) >= get_pri(c):
# 上一个操作符出栈
output += stack.pop()
# 当前运算符入栈
stack.append(c)
# 如果是左括号
elif c == "(":
# 入栈
stack.append(c)
# 如果是右括号
elif c == ")":
# 栈非空时
while stack:
# 上一个操作符出栈
# 上一个是括号退出循环
top = stack.pop()
if top == "(":
break
output += top
else:
output += c
# 弹出剩余操作符
while stack:
output += stack.pop()
return output
# 计算后缀表达式
def calculate(string):
stack = []
for c in string:
# 如果是运算符
if is_op(c):
# [右面的操作数先出栈]
b = stack.pop()
a = stack.pop()
stack.append(eval(f"{a}{c}{b}"))
else:
# 操作数直接入栈
stack.append(c)
# [最后一个必是操作数]
return stack.pop()
cs = convert(string)
print(cs)
result = calculate(cs)
print(result)
原文:https://www.cnblogs.com/aminor/p/15052929.html