修改ArrayStack实现,使堆栈的容量限制为maxlen

2024-03-29 01:39:17 发布

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

我需要帮助理解此任务:

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()

Tags: thetoselfdatalenreturnifis
1条回答
网友
1楼 · 发布于 2024-03-29 01:39:17

我希望您知道代码中的前两个语句会引发错误。您需要声明您的异常,为此我建议您查看Proper way to declare custom exceptions in modern Python?。你知道吗

您可以在__init__中设置maxlen

def __init__(self, maxlen=None):
    self.maxlen=maxlen

现在,is_full需要修改,以根据self.maxlenNone还是一个数字采取不同的行动。如果None,那么堆栈永远不会填满(至少理论上是这样)。你知道吗

相关问题 更多 >