如何在我的代码

时间:2018-02-08 16:10:39

标签: python-3.x

我刚刚开始编程几个月前,我不知道该怎么做我的任务。我需要修改ArrayStack实现,以便堆栈的容量有限 到maxlen元素,其中maxlen是构造函数的可选参数(默认为 没有)。如果在堆栈满容量时调用push,则抛出一个Full异常(定义类似于 空)。

class Empty(Exception):
pass

class ArrayStack:
"""LIFO Stack implementation using a Python list as underlying storage."""


  def __init__(self):
"""Create an empty stack."""
self._data = []                       # nonpublic list instance

   def __len__(self):
"""Return the number of elements in the stack."""
return len(self._data)

   def is_empty(self):
"""Return True if the stack is empty."""
return len(self._data) == 0

  def push(self, e):
"""Add element e to the top of the stack."""
self._data.append(e)                  # new item stored at end of list

 def top(self):
 """Return (but do not remove) the element at the top of the stack.

Raise Empty exception if the stack is empty.
"""
if self.is_empty():
  raise Empty('Stack is empty')
return self._data[-1]                 # the last item in the list

def pop(self):
"""Remove and return the element from the top of the stack (i.e., LIFO).

Raise Empty exception if the stack is empty.
"""
if self.is_empty():
  raise Empty('Stack is empty')
return self._data.pop()               # remove last item from list

1 个答案:

答案 0 :(得分:1)

只需将参数添加到构造函数和push方法

即可
class Empty(Exception):
    pass

class ArrayStack:
"""LIFO Stack implementation using a Python list as underlying storage."""


    def __init__(self, maxlen=None):
        """Create an empty stack."""
        self._data = []                      # nonpublic list instance
        self.maxlen=maxlen

    def __len__(self):
        """Return the number of elements in the stack."""
        return len(self._data)

    def is_empty(self):
        """Return True if the stack is empty."""
        return len(self._data) == 0

    def push(self, e):
        """Add element e to the top of the stack."""
        if len(self._data) == self.maxlen:
            raise Exception # Whatever exception you want
        self._data.append(e)                  # new item stored at end of list

    def top(self):
        """Return (but do not remove) the element at the top of the stack.

           Raise Empty exception if the stack is empty.
        """
        if self.is_empty():
            raise Empty('Stack is empty')
        return self._data[-1]                 # the last item in the list

    def pop(self):
        """Remove and return the element from the top of the stack (i.e., LIFO).
           Raise Empty exception if the stack is empty.
        """
        if self.is_empty():
            raise Empty('Stack is empty')
        return self._data.pop()               # remove last item from list