算法:栈的应用,简化模板题。
对应到y总的模板题 表达式求值.
Pyhton代码
num = []
op = []
def new_eval():
b = num.pop()
a = num.pop()
x = a * n + b * m
num.append(x)
n,m = map(int,input().split())
li = input()
i = 0
while i < len(li):
c = li[i]
if c.isdigit() or c == '-':
flag = False
if c == '-':
flag = True
x = 0
if flag:
j = i + 1
else:
j = i
while j < len(li) and li[j].isdigit():
x = x * 10 + int(li[j])
j += 1
i = j - 1
if flag:
x = -x
num.append(x)
elif c == '(':
op.append(c)
elif c == ')':
new_eval()
op.pop()
i += 1
print(num[0])