使用Python中的栈来评估中缀表达式:我找不到错误。

3

看了这个代码两天后,我决定寻求帮助。这是我第一次提问,请耐心等待。

我的编码经验很少,知识也仅限于所示代码,尽量保持简单。

为了完成我正在上的一个课程,我必须编写代码以正确执行操作顺序,以下是我的成品代码:

import operator

class stack:
    def __init__(self):
        self._stack = []

    def __len__(self):
        return len(self._stack)

    def is_empty(self):
        return len(self._stack) == 0

    def push(self, e):
        self._stack.append(e)

    def top(self):
        if self.is_empty():
            print ('stack is empty')
        return self._stack[-1]

    def pop(self):
        if self.is_empty():
            print ('stack is empty')
            return
        return self._stack.pop()

def apply(a,b,c):

    ops2 = {"+": operator.add,
           "-": operator.sub,
           "*": operator.mul,
           "/": operator.truediv }
    op_char = c
    op_func = ops2[op_char]
    result = op_func(float(a), float(b))
    return result

user = '6 - 5 ( 5 - 3 ) * (4 + 2 )' 
#user = input("Enter an expression: ")
print(user)
exp = user.split()
nums = '1234567890'
ops = ['*', '/', '+', '-']
par = ['(', ')']

num = stack()
op = stack()

for each in exp:
    print(each)
    if each in nums:
        num.push(each)

    if  each == par[0]:
        op.push(each)

    if each in ops:            
        if each == ops[2] or ops[3]:
            op.push(each)

        if each == ops[0] or ops[1]:
                while op.top() == (ops[2] or ops[3]) and len(op) > 0 and len(num) >= 2:
                    ans = apply(num.pop(),num.pop(),op.pop())
                    num.push(ans)   
                    op.push(each)
    if each == par[1]:
        while op.top() != "(":
            ans = apply(num.pop(),num.pop(),op.pop()) # this line is poping the empty stack
            num.push(ans)
        op.pop()

while op.is_empty() != True:
    ans = apply(num.pop(),num.pop(),op.pop())
    num.push(ans)
print(ans)

或许我可以帮忙翻译... 当我运行这段代码时,if each == par[1] 循环中出现了“栈为空”的错误,我无法弄清楚原因。我使用的表达式应该等于 -6.0。希望能得到帮助。 编辑:在更改代码后,我遇到了类似的情况,并且认为我在某个地方出错了。再次检查代码后,我仍然找不到错误。任何帮助都将不胜感激。

1
我刚刚看到你又进行了一次编辑。通常来说,最好在一个新的问题中提出进一步的问题,而不是编辑您现有的问题,因为对您的问题的编辑通常不会引起太多关注。此外,这将为您提供包括您遇到的具体错误的机会。(顺便说一下,欢迎来到SO!) - Justin O Barber
谢谢你提供的信息,我不太确定该如何处理。 - codster303
我想说我已经弄明白了。 - codster303
1个回答

3

很抱歉,这段代码存在其他问题(在您修复下面的问题后会发现),但是您在问题中提到的问题来自于您的pop方法:

def pop(self):
    if self.is_empty():
        print ('stack is empty')  # still proceeds to the next line
    return self._stack.pop()  # won't work if self._stack is empty

这会引发一个 IndexError,因为您无法从空列表中执行 pop 操作,而您的返回语句将在列表为空或不为空时都运行。也许您想要像下面这样做:

def pop(self):
    if self.is_empty():
        print ('stack is empty')
        return  # now you need to deal with the returned None value
    return self._stack.pop()  # only if not empty

@user3404267 当然可以。希望能对你有所帮助。 - Justin O Barber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接