AcWing 3302. 表达式求值
原题链接
中等
作者:
开朗且社恐
,
2024-07-26 23:20:24
,
所有人可见
,
阅读 1
def Eval():
b = num.pop()
a = num.pop()
c = op.pop()
if c == "+":
x = a + b
elif c == "-":
x = a - b
elif c == "*":
x = a * b
else:
x = int(a / b)
num.append(x)
string = input()
num = [] # 数字栈
op = [] # 操作符栈
pr = {"-": 1, "+": 1, "*": 2, "/": 2}
i = 0
while i < len(string):
c = string[i]
if c.isdigit():
x, j = 0, i
while j < len(string) and string[j].isdigit():
x = x * 10 + int(string[j])
j += 1
i = j - 1
num.append(x)
elif c == "(":
op.append(c)
elif c == ")":
while op[-1] != "(":
Eval()
op.pop()
else:
while op and op[-1] != "(" and pr[op[-1]] >= pr[c]:
Eval()
op.append(c)
i += 1
while op:
Eval()
print(num[-1])