data = """
3+51*4-23/(3+8)-5
(42+33*(2+5))-7*8
"""
nex = [] # 存储括号对应关系
token = []
# 预处理
def pre(s):
global token
global nex
token = []
nex = []
stack = []
i = 0
while i < len(s):
if s[i] == '(':
token.append("(")
i += 1
elif s[i] == ')':
token.append(")")
i += 1
elif s[i] in "+-*/":
token.append(s[i])
i += 1
elif s[i].isspace():
i += 1
else:
v = ""
while i < len(s) and s[i].isdigit():
v += s[i]
i += 1
token.append(v)
i = 0
nex = [0] * len(token)
while i < len(token):
if token[i] == "(":
stack.append(i)
i += 1
elif token[i] == ")":
x = stack.pop()
nex[i] = x
nex[x] = i
i += 1
else:
i += 1
# 运算符优先级
def priority(op):
return {"+": 0, "-": 0, "*": 1, "/": 1}[op]
# 计算值
def cal(x, y, op):
if op == "+":
return x + y
elif op == "-":
return x - y
elif op == "*":
return x * y
else:
return x / y
# 将token[f:t]转换成结点
def node(token, f, t):
r = {}
minOp = -1
minOpPriority = 0xfffffff
while token[f] == "(" and token[t] == ")":
f += 1
t -= 1
if f == t:
r["value"] = int(token[f])
return r
i = f
while i <= t:
if token[i] == '(':
i = nex[i] + 1
elif token[i] in "+-*/":
op = priority(token[i])
if op <= minOpPriority:
minOp = i
minOpPriority = op
i += 1
else:
i += 1
r["left"] = node(token, f, minOp - 1)
r["right"] = node(token, minOp + 1, t)
r["op"] = token[minOp]
r["value"] = cal(r["left"]["value"], r["right"]["value"], r["op"])
return r
# 打印后序
def houxu(node):
if not "op" in node:
return [node["value"]]
l = houxu(node["left"])
r = houxu(node["right"])
op = node["op"]
return l + r + [op]
def main(s):
s = s.strip()
pre(s)
n = node(token, 0, len(token) - 1)
print(houxu(n))
return n["value"]
for i in data.split():
print(i, "=", eval(i), main(i))