-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharraystack.py
More file actions
54 lines (46 loc) · 1.77 KB
/
arraystack.py
File metadata and controls
54 lines (46 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
from arrays import Array
from abstractstack import AbstractStack
class ArrayStack(AbstractStack):
"""An array-based stack implementation."""
DEFAULT_CAPACITY = 10 # For all array stacks
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the
content of sourceCollection, if it's present."""
self._items = Array(ArrayStack.DEFAULT_CAPACITY)
AbstractStack.__init__(self, sourceCollection)
# Accessor methods
def __iter__(self):
"""Supports iteration over a view of self.
Visits items from bottom to top of stack."""
cursor = 0
while cursor < len(self):
yield self._items[cursor]
cursor += 1
def peek(self):
"""Returns the item at top of the stack.
Precondition: the stack is not empty.
Raise KeyError if the stack is empty."""
if self.isEmpty():
raise KeyError("The stack is empty.")
return self._items[len(self) - 1]
# Mutator mehtods
def clear(self):
"""Makes self become empty."""
self._size = 0
self._items = Array(ArrayStack.DEFAULT_CAPACITY)
def push(self, item):
"""Insert item at top of the stack."""
# Resize array here if necessary
self._items[len(self)] = item
self._size += 1
def pop(self):
"""Removes and returns the item at top of the stack.
Precondition: the stack is not empty.
Raise KeyError if the stack is empty.
Postcondition: the top item is removed from the stack."""
if self.isEmpty():
raise KeyError("The stack is empty.")
oldItem = self._items[len(self)]
self._size -= 1
# Resize array here if necessary
return oldItem