Home > Back-end >  Behaviour of set-intersection of objects
Behaviour of set-intersection of objects

Time:11-21

I stumbled upon this uncertainty in one of my programs:
Suppose we have a Class deriving from int with a custom attribute.

class A(int):
    def __new__(cls, value, *args, **kwargs):
        return super(cls, cls).__new__(cls, value)

    def __init__(self, _, a):
        self.a = a

Objects of this class are now used in a Set.

set1 = {A(2, 5), A(3, 2)}
set2 = {A(3, 7), A(5, 5)}

How would I now know the output of the following operations?

x, = set1 & set2
print(x.a)

x, = set2 & set1
print(x.a)

x, = set1.intersection(set2)
print(x.a)
...

It appeared to me in various tests that the result is rather random, could somebody explain this behaviour?
Thank you in advance :)

CodePudding user response:

You intrigued me so much that I looked into source code and it became quite logical. We looped over smaller set and search every element in bigger one. When both sets has equal size, the order matters (that's why you get different results in your case), otherwise the elements taken will always belong to smaller set.

  • Related