# CSI31_Lecture25_set.py from copy import copy class Set: def __init__(self,elements): self._elements = [] for item in elements: # iterate over the sequence elements if item not in self._elements: # exclude duplicates self._elements.append(item) def addElement(self,x): if x not in self._elements: self._elements.append(x) def deleteElement(self,x): try: self._elements.remove(x) except: print(x, "is not in the set") def member(self,x): return x in self._elements def intersection(self,set2): newList = [] # choose the set with smaller number of elements if len(self._elements) < len(set2._elements): for item in self._elements: # iterate over the elements of this set if set2.memeber(item): # if item is also an element of set2 newList.append(item) else: # iterate over the elements of set2 for item in set2._elements: if item in self._elements: # if item is also an element of this set newList.append(item) return Set(newList) def union(self,set2): newList = copy(self._elements) # copy all elements of set to new list for item in set2._elements: # iterate over the elements of the second set if item not in newList: newList.append(item) return Set(newList) def subtract(set2): newList = [] for item in self._elements: # iterate over the elements of this set if not set2.member(item): # check if the element is not in the set2 newList.append(item) return Set(newList)