5 条题解

  • 0
    @ 2023-11-11 19:28:22
    def zenslis(lis):
        ops = '()*/+-';s='';lis2 = []
        for i in lis:
            if '0' <= i <= '9':
                s += i
                num = True
            elif i in ops:
                if num == True:
                    lis2.append(s)
                    s=''
                    num = False
                lis2.append(i)
        if s:
            lis2.append(s)
        return lis2
    
    def intpost(expr):
        ops = {'(':0,')':0,'**':1,'*':2,'/':2,'+':3,'-':3}
        stack = []
        post = []
        for z in expr:
            if z not in ops:
                post.append(z)
            else:
                if z != ')' and (not stack or z == '(' or stack[-1] == '(' or ops[z] < ops[stack[-1]]):
                    stack.append(z)
                elif z == ')':
                    while True:
                        x = stack.pop()
                        if x != '(':
                            post.append(x)
                        else:
                            break
                else:
                    while True:
                        if stack and stack[-1] != '(' and ops[z] >= ops[stack[-1]]:
                            post.append(stack.pop())
                        else:
                            stack.append(z)
                            break
            #print(stack)
        while stack:
            post.append(stack.pop())
        return post
    

    运行代码

    if __name__ == '__main__':
        s = input()
        lis = zenslis(s)
        post = intpost(lis)
        print(' '.join(post))
    
    • @ 2023-11-22 11:40:19

      在发题解之前请先认真阅读题目= = 题目并不要求输出中缀表达式计算结果

信息

ID
800
时间
1000ms
内存
256MiB
难度
7
标签
(无)
递交数
840
已通过
167
上传者