python程序将中缀转换为后缀时出错

2024-06-02 06:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了python程序,将中缀数学表达式转换为后缀。它对一些输入非常有效,例如A-((B+C)*D-E)*F或(A+B)*C。但是当我提交代码评分站点时,它说存在运行时错误。你能告诉我为什么我的代码有运行时错误以及如何修复它吗

str = input()
result = ''
stack = []

def getorder(c):
    return {'*':5, '/':5, '+':3, '-':3, '(':1}[c]

def whoisfirst(x, y):
    if(getorder(x) > getorder(y)):
        return 1;
    elif(getorder(x) < getorder(y)):
        return -1;
    else:
        return 0;

for i in str:
    if(i.isalpha()):
        result += i
    else:
        if (i == '('):
            stack.append(i)
            continue
        elif (i == ')'):
            while True:
                result += stack.pop(-1)

                if(stack[-1] == '('):
                    stack.pop(-1)
                    break
            continue


        if not stack:
            stack.append(i)
        else:
            while (whoisfirst(i, stack[-1]) != 1):
                result += stack.pop(-1)

                if not stack:
                    break
            stack.append(i)

while stack:
    result += stack.pop(-1)

print(result)

Tags: 代码returnifstackdef错误resultpop