-1

I need help understanding this task:

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

This is what I am fiddling with

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()
CDspace
  • 2,639
  • 18
  • 30
  • 36

1 Answers1

0

I expect that you know that the first two statements in your code raise errors. You need to declare your exceptions, for which I suggest that you look at Proper way to declare custom exceptions in modern Python?.

You would set maxlen in the __init__:

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

Now, is_full would need modifying to act differently depending on whether self.maxlen was None or a number. If None then the stack would never fill (at least theoretically).

Bill Bell
  • 21,021
  • 5
  • 43
  • 58