-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathlinearbag.py
More file actions
35 lines (29 loc) · 948 Bytes
/
linearbag.py
File metadata and controls
35 lines (29 loc) · 948 Bytes
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
#implements Bag ADT container using a Python list structure
class Bag:
def __init__(self):
self._theItems = list()
def __len__(self):
return len(self._theItems)
def __contains__(self, item):
return item in self._theItems
def add(self, item):
self._theItems.append(item)
def remove(self, item):
assert item in self._theItems, "The item must be in the bag."
ndx = self._theItems.index(item)
return self._theItems.pop(ndx)
def __iter__(self):
return _BagIterator(self._theItems)
class _BagIterator:
def __init__(self, theList):
self._bagItems = theList
self._curItem = 0
def __iter__(self):
return self
def __next__(self):
if self._curItem < len(self._bagItems):
item = self._bagItems[self._curItem]
self._curItem += 1
return item
else:
raise StopIteration