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
| class IntSet(object):
"""An IntSet is a set of integers
The values contained in the set are represented by a list of integers: self.__vals
Each integer in the set occurs in self.__vals exactly once.
"""
def __init__(self, /, *v):
"""Creates a set of integers
input -- self : instance of class IntSet
"""
self.__vals=list()
for x in v: self.insert(x)
# __init__()
def __str__(self):
"""Returns a string representation of self
input -- self : instance of class IntSet
output -- string: shows the list of elements in self (string type)
"""
# TODO
return "{%s}" % ", ".join(map(str, self.__vals))
# __str__()
def __contains__(self, e):
"""Returns True if e is in self, and False otherwise
input -- self : instance of class IntSet
-- e : integer, the value to be tested
output -- bool, is True if e is in self, False otherwise
"""
return e in self.__vals
#__contains__()
def __iter__(self):
"""Make an iteration of values
input -- self : instance of class IntSet
output -- None
"""
yield from self.__vals
# __iter__()
def insert(self, e):
"""Inserts e into self
input -- self : instance of class IntSet
-- e : integer
"""
if e not in self: self.__vals.append(e)
# insert()
def remove(self, e):
"""Removes e from self. If e is not in self, do nothing
Raises ValueError if e is not in self
input -- self : instance of class IntSet
-- e : integer
output -- bool, True if e has been removed
"""
if e in self:
self.__vals.remove(e)
return True
# if
return False
# remove()
def intersect(self, other):
"""Returns the intersection of the sets self and other
input -- self : instance of class IntSet
-- other : instance of class IntSet
output -- instance of class IntSet, the intersection of self and other
"""
# TODO
commun = self.__class__()
for number in self:
if number in other: commun.insert(number)
return commun
# intersect()
# class IntSet
class toto(IntSet): pass
s1 = toto(1, 5, 4, 3)
print('s1:', s1, type(s1))
s2 = toto(4, 6, 7, 1)
print('s2:', s2, type(s2))
s = s1.intersect(s2)
print('s:', s, type(s))
s = s2.intersect(s1)
print('s:', s, type(s)) |
Partager