我需要帮助理解此任务:
Modify the ArrayStack implementation so that the stack’s capacity is limited to maxlen elements, where maxlen is an optional parameter to the constructor (that defaults to None). If push is called when the stack is at full capacity, throw a Full exception (defined similarly to Empty).
这就是我在摆弄的东西
from exceptions import Empty
from exceptions import Full
class ArrayStack:
def __init__(self):
self._data = [] # nonpublic list instance
def __len__(self):
return len(self._data)
def is_empty(self):
return len(self._data) == 0
def is_full(self):
return len(self.data) == n-1
def push(self, e):
self._data.append(e) # new item stored at end of list
if self.is_full():
raise Full('Stack is full')
return self._data[n-1]
def top(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data[-1]
def pop(self):
if self.is_empty():
raise Empty('Stack is empty')
return self._data.pop()
我希望您知道代码中的前两个语句会引发错误。您需要声明您的异常,为此我建议您查看Proper way to declare custom exceptions in modern Python?。你知道吗
您可以在
__init__
中设置maxlen
:现在,
is_full
需要修改,以根据self.maxlen
是None
还是一个数字采取不同的行动。如果None
,那么堆栈永远不会填满(至少理论上是这样)。你知道吗相关问题 更多 >
编程相关推荐