Python:NameError:未定义名称“Stack”?

2024-05-16 08:56:10 发布

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

我正在尝试了解堆栈,并在该网站上找到以下代码:http://interactivepython.org/runestone/static/pythonds/BasicDS/stacks.html

s = Stack()

s.push('a')
print(s.is_empty())
print(s.peek())
print(s.is_empty())
print(s.pop())
print(s.is_empty())

运行代码时,我得到错误NameError: name 'Stack' is not defined。有人能帮忙吗?在


Tags: 代码orghttpisstack堆栈网站static
3条回答

堆栈不是python中的内置类型。您需要先定义它(或从其他模块导入)。在您的例子中,您需要首先运行ActiveCode 1。在

根据另一个答案

Stack is not built-in type in Python.

因此,它必须进行定义,因为在交互式python教程中没有声明任何库。在

我从交互式python教程中学习了Stack()类,您的代码应该是这样的

class Stack:
     def __init__(self):
         self.items = []

     # I have changed method name isEmpty to is_empty
     # because in your code you have used is_empty
     def is_empty(self):
         return self.items == []

     def push(self, item):
         self.items.append(item)

     def pop(self):
         return self.items.pop()

     def peek(self):
         return self.items[len(self.items)-1]

     def size(self):
         return len(self.items)

s = Stack()
s.push('a')
print(s.is_empty())
print(s.peek())
print(s.is_empty())
print(s.pop())
print(s.is_empty())

输出

^{2}$

Python list实际上的行为是like stacks:append()将一个项放在堆栈的顶部(它类似于来自其他编程语言或其他实现的push(),而pop()可用于从堆栈顶部检索项。在

相关问题 更多 >