题解 | 四则运算 - 清晰一些的栈算法

四则运算

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刷题#
全部评论

相关推荐

你背过凌晨4点的八股文么:简历挂了的话会是流程终止,像我一样
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务