Reputation: 567
I reimplemented the set in python but i have some problem with multiple intersection.... I followed the book Learning Python but i have problem with my code
class Set:
def __init__(self,value=[]):
self.data = []
self.remDupli(value)
def remDupli(self,val):
for i in val:
if i not in self.data:
self.data.append(i)
def intersect(self,other):
val=[]
for i in self.data:
for k in other:
if i == k:
val.append(i)
return Set(val)
def union(self,other):
val=self.data
for i in other:
if i not in self.data:
val.append(i)
return Set(val)
def __or__(self,a): return self.union(a)
def __and__(self,a): return self.intersect(a)
def __len__(self): return len(self.data)
def __getitem__(self,key): return self.data[key]
def __repr__(self): return 'Set: ' +repr(self.data)
class Extend(Set):
def intersect(self, *others):
val = []
for i in self:
for x in others:
if i in x:
val.append(i)
return Set(val)
but when I run this:
x = Extend([1,2,3,4])
y = Extend([3,4,5])
z = Extend([0,1,2])
print(x & y & z)
print(x.intersect(y, z))
I have two different behavior
Set: []
Set: [1, 2, 3, 4]
I don't understand because the second is different, in my opinion they should have the same behavior, anyone can help me?
Upvotes: 1
Views: 866
Reputation: 24439
Extend.intersect
does not calculate intersection between many sets. It calculates intersection between self
and union of others
.
The results are different because x & y & z
calls Extend.intersect(Extend.intersect(x,y), z)
, while x.intersect(y,z)
calls Extend.intersect(x, *[y,z])
and given what Extend.intersect
actually does, those happen to be different operations.
Upvotes: 6