【问题标题】:I implement a stack in python, however the "push" method doesn't work我在python中实现了一个堆栈,但是“push”方法不起作用
【发布时间】:2021-02-09 02:59:33
【问题描述】:

我还是python的新手,所以在练习实现一个堆栈,不明白为什么push方法不起作用。我的代码如下:

class Stack:

    def __init__(self):
        self.top = None
        self.size = 0

    def isEmpty(self):
        return self.top == None
    
    def push(self, value):
        node = Node(value, self.top)        
        self.top = node
        self.size += 1

    def pop(self):
        assert not self.isEmpty, "Error: The stack is empty"
        node = self.top
        self.top = self.top.next
        return node.value

class Node:

    def __init__(self, value, link):
        self.value = value
        self.next = link
    

def main():
    
    stack = Stack()
    assert stack.isEmpty, "--> Error: isEmpty"
    stack.push(1)
    assert not stack.isEmpty, "--> Error: not isEmpty"  
    print(stack.pop())  

if __name__ == "__main__":
    main()

这是出口:

文件“c:”,第 33 行,在 main 断言不是 stack.isEmpty,“--> 错误:不是 isEmpty”
AssertionError: --> 错误:不是 isEmpty

【问题讨论】:

  • 我想你忘了打电话给stack.isEmpty()
  • 谢谢,是的,我做了更改,但是“推送”功能一直失败,尝试“弹出”时报告以下错误:文件“c:”,第17行,在弹出断言中not self.isEmpty, "Error: The stack is empty" AssertionError: Error: The stack is empty
  • 您是不是也想说:self.isEmpty()

标签: python stack


【解决方案1】:

stack.isEmpty 是一个函数,而stack.isEmpty() 是一个函数调用(返回一个布尔值)。

编辑:如果您想要一个属性isEmpty,请在__init__() 中声明一个属性,并确保在对对象进行更改时更新它。这样您就可以引用stack.isEmpty 而无需调用函数。这更多是个人喜好。

【讨论】:

  • 非常感谢,我应该考虑到这一点,但是当我进入“pop”方法时,我仍然得到错误:File "c:", line 17, in pop assert not self.isEmpty, "Error: The stack is empty" AssertionError: Error: The stack is empty 这意味着“push”方法一直失败
  • 您在assert 语句中犯了同样的错误,您需要致电self.isEmpty()
  • 天哪,没错,我在语法上有一些非常愚蠢的错误。现在完美运行
  • 发生在我们最好的人身上 - 很高兴你能成功! @爱德华
猜你喜欢
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 2021-03-04
  • 2013-03-02
  • 2023-01-17
  • 1970-01-01
  • 2011-05-04
  • 1970-01-01
相关资源
最近更新 更多