Create a file named Setpy with a class named Set that implem
Solution
Set.py :
class Set:
def __init__(self, *args):
self._dict = {}
for arg in args:
self.add(arg)
def extend(self, args):
\"\"\" Add several items at once. \"\"\"
for arg in args:
self.add(arg)
def add(self, item):
\"\"\" Add one item to the set. \"\"\"
self._dict[item] = item
def remove(self, item):
\"\"\" Remove an item from the set. \"\"\"
del self._dict[item]
def printList(self):
for item in self:
print(item)
def contains(self, item):
\"\"\" Check whether the set contains a certain item. \"\"\"
for i in self:
if i == item:
return \'true\'
return \'false\'
def isSubsetOf(s1,s2):
for item in s2:
if s1.contains(item) == \'false\':
return \'false\'
return \'true\'
def __getitem__(self, index):
\"\"\" Support the \'for item in set:\' protocol. \"\"\"
return self._dict.keys( )[index]
def __iter__(self):
\"\"\" Better support of \'for item in set:\' via Python 2.2 iterators \"\"\"
return iter(self._dict.copy( ))
def __len__(self):
\"\"\" Return the number of items in the set \"\"\"
return len(self._dict)
def __copy__(self):
return Set(self)
def union(s1, s2):
import copy
result = copy.copy(s1)
for item in s2:
result.add(item)
return result
def __add__(s1,s2):
result = s1
for item in s2:
result.add(item)
return result
def __sub__(s1,s2):
result=s1;
for item in s2:
if s1.contains(item):
result.remove(item)
return result
def __eq__(s1,s2):
for items in s1:
if s2.contains(items) == \'false\':
return False
return True
def __hash__(self):
return hash(self._dict)
def __ne__(s1,s2):
for items in s1:
if s2.contains(items) == \'true\':
return True
return False
main.py
# Hello World program in Python
from Set import *
s1 = Set(4,3)
s1.add(1)
s1.add(2)
s2= Set(4,3)
print(\"Set s1: \")
s1.printList()
print(\"Set s2: \")
s2.printList()
if s1.isSubsetOf(s2) == \'true\':
print(\"subset\")
else:
print(\"no subset\")
s=s1+s2
print(\"Addition of Sets : \")
s.printList()
s=s1-s2
print(\"Intersection of Sets : \")
s.printList()
print(\"equality :\")
if s1==s2:
print(\"s1 == s2\")
if s1!= s2:
print(\"s1 !=s2\")


