# Implementation of iter
class _SetIterator:
def __init__(self, theList):
self._setItems = theList
self._curItem = 0
def __iter__(self):
return self
def next(self):
if self._curItem < len(self._setItems):
item = self._setItems[self._curItem]
self._curItem += 1
return item
else:
raise StopIteration
# Implementation of the Set ADT container using a Python list
class mySet:
# Creates an empty set instance
def __init__(self):
self._theElements = list()
# Returns the number of items in the set
def __len__(self):
return len(self._theElements)
# Determines if an element is in the set
def __contains__(self, element):
return element in self._theElements
# Adds a new unique element to the set
def add(self, element):
if element not in self:
self._theElements.append(element)
# Removes an element from the set
def remove(self, element):
assert element in self, "The element must be in the set."
self._theElements.remove(element)
# Determines if two sets are equal
def __eq__(self, setB):
if len(self) != len(setB):
return False
else:
return self.isSubsetOf(setB)
# Determines if this set is a subset of setB
def isSubsetOf(self, setB):
for element in self:
if element not in setB:
return False
return True
# Creates a new set from the union of this set and setB
def union(self, setB):
newSet = mySet()
newSet._theElements.extend(self._theElements)
for element in setB:
if element not in self:
newSet._theElements.append(element)
return newSet
# Creates a new set from the intersection
def interset(self, setB):
newSet = mySet()
for element in setB:
if element in self:
newSet._theElements.append(element)
return newSet
def difference(self, setB):
newSet = mySet()
for element in self:
if element not in setB:
newSet._theElements.append(element)
return newSet
# Returns an iterator for traversing the list of items
def __iter__(self):
return _SetIterator(self._theElements)
def test_linearset():
# import mySet
from linearset import mySet
# init a set named smith
smith = mySet()
smith.add('CSCI-112')
smith.add('MATH-121')
smith.add('HIST-340')
smith.add('ECON-101')
# init a set named roberts
roberts = mySet()
roberts.add('POL-101')
roberts.add('ANTH-230')
roberts.add('CSCI-112')
roberts.add('ECON-101')
for a in smith:
print a
if __name__ == "__main__":
test_linearset()