题解 | 四则运算 - 清晰一些的栈算法
四则运算
https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e
#栈算法
s = input().replace('[','(').replace(']',')').replace('{','(').replace('}',')')
def groupsum(sx):
stack=[]
onhold=0
temp=''
for i in range(len(sx)+1):
if i==len(sx):
x='_'
else:
x=sx[i]
if x in ['+','-','*','/','_']:
#stack更新条件
if len(temp)>0:
if onhold==1:
stack[-1]=stack[-1]*int(temp)
onhold=0
elif onhold==2:
stack[-1]=stack[-1]//int(temp)
onhold=0
else:
stack.append(int(temp))
#刷新temp
temp=''
if x=='-':
temp='-'
if x =='*':
onhold=1
elif x=='/':
onhold=2
else:
temp+=x
return str(sum(stack))
while '(' in s:
s0=s.split('(')[-1].split(')')[0]
s=s.replace('('+s0+')',groupsum(s0))
s=s.replace('--','+')
print(groupsum(s))
#python刷题#
腾讯公司福利 1152人发布
查看23道真题和解析