Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Behaviour of set-intersection of objects

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 🙂

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading