-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharraybag.py
More file actions
57 lines (48 loc) · 1.77 KB
/
arraybag.py
File metadata and controls
57 lines (48 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
55
56
57
from arrays import Array
from abstractbag import AbstractBag
class ArrayBag(AbstractBag):
"""An array-based bag implementation."""
# Class variable
DEFAULT_CAPACITY = 10
# Constructor
def __init__(self, sourceCollection=None):
"""Sets the initial state of self, which includes the
content of sourceCollection, if it's present."""
self._items = Array(ArrayBag.DEFAULT_CAPACITY)
AbstractBag.__init__(self, sourceCollection)
# Accessor methods
def __iter__(self):
"""Supports iteration over a view of self."""
cursor = 0
while cursor < len(self):
yield self._items[cursor]
cursor += 1
# Mutator methods
def clear(self):
"""Make self become empty."""
self._size = 0
self._items = Array(ArrayBag.DEFAULT_CAPACITY)
def add(self, item):
"""Add item to self."""
# Check array memory here and increase it if necessary
self._items[len(self)] = item
self._size += 1
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item in not in self.
Postcondition: item is removed from self."""
# Check precondition and raise if necessary
if not item in self:
raise KeyError(str(item) + " not in bag")
# Search for index of target item
targetIndex = 0
for targetItem in self:
if targetItem == item:
break
targetIndex += 1
# Shift items to the left of target up by one position
for i in range(targetIndex, len(self) - 1):
self._items[i] = self._items[i + 1]
# Decrement logical size
self._size -= 1
# Check array memory here and decrease it if necessary