1

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?

1
  • x.intersect(y.intersect(z)) will have the same behaviour as x & y & z Commented May 29, 2012 at 10:35

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Can I change my code in order to have the same behavior? or do I have only to change way to call in this way x.intersect(y.intersect(z))?
@fege Depends, but I feel that your real problem is that you got the algorithm wrong, so you have to fix it, not the calling code.
if all(i in x for x in others): val.append(i)
I think the Extend.intersect should use the base implementation defined in the Set class. BTW, I would expect Extend.intersect to return an Extend object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.