-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedBag.py
96 lines (73 loc) · 2.18 KB
/
linkedBag.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
"""
File: linkedBag.py
Project: 4
Author: James Lawson, Harrison Pinkerton, Laruie Jones
Creates a linked bag
"""
from node import Node
from abstractBag import AbstractBag
class LinkedBag(AbstractBag):
"""A link-based implemention of a bag."""
# Constructor
def __init__(self, sourceCollection = None):
"""Sets the initial state of self,
which includes the contents of sourceCollection,
if it is present."""
self._items = None
super().__init__(sourceCollection)
# Accessor Methods
def __iter__(self):
before = super().getModCount()
cursor = self._items
while cursor != None:
yield cursor.data
after = super().getModCount()
if before == after:
cursor = cursor.next
else:
raise AttributeError("Illegal modification of the backing store.")
# Mutator Methods
def clear(self):
self._size = 0
self._items = None
super().resetSizeAndModCount()
def add(self, item):
self._items = Node(item, self._items)
self._size += 1
super().incModCount()
def remove(self, item):
"""Precondition: item is in self.
Raises: KeyError if item in not in self.
Postcondition: item is removed from self."""
cursor = self._items
trailer = None
if item not in self:
raise IndexError("item is removed from self")
for i in self:
if item == i:
break
trailer = cursor
cursor = cursor.next
if cursor == self._items:
self._items = None
else:
trailer.next = cursor
self._size -= 1
super().incModCount()
if __name__ == "__main__":
#a = LinkedBag(["hi", "bye", "cat"])
#b = LinkedBag(["a", "b", "c"])
a = LinkedBag()
b = LinkedBag(["a", "b", "c"])
a.add("hi")
a.add("bye")
a.add("cat")
print(a)
print(type(a + b))
print(a + b)
a2 = LinkedBag(a)
print(a2)
for item in a:
print(item)
a.clear()
print(a)