2

What is the fastest way to check if two sets in Python have at least one common element? The desired output is a True/False.

e.g. I tried with set.intersection(), but I would like to avoid checking all the elements in both sets.

set.intersection({1,2,3}, {8,9,2})
>>> {2}

NOTE: I'm searching for a very efficient solution that works with Python sets (I'm not asking about lists)

Dos
  • 2,250
  • 1
  • 29
  • 39
  • 1
    Do you want to return `true` as **if two sets have at least one common element** or do you want to return `2`? – JvdV Apr 04 '20 at 14:06
  • 2
    How about `not`[`isdisjoint`](https://docs.python.org/3/library/stdtypes.html#frozenset.isdisjoint)? – khelwood Apr 04 '20 at 14:06
  • I want to return True. Thank for the note, I edited the question. – Dos Apr 04 '20 at 14:13
  • Found a dup. So does this answer your question? [one-liner to check if at least one item in list exists in another list?](https://stackoverflow.com/questions/10668282/one-liner-to-check-if-at-least-one-item-in-list-exists-in-another-list) – JvdV Apr 04 '20 at 14:28
  • Lists are definitively different from sets! I searching for a very efficient solution with sets – Dos Apr 04 '20 at 14:45

2 Answers2

6

{1,2,3}.isdisjoint({4,5,6}) will return true since there is no intersection.

jithin
  • 1,412
  • 2
  • 17
  • 27
1
def intersect(a, b):
    if len(a) > len(b):
        a, b = b, a   
    for c in a:
        if c in b:
            return c

The above code is similar to the implementation of intersection( ), except that this version returns the first element that is matched. You could also return true if required, instead of the first matched element.

Deepu
  • 7,592
  • 4
  • 25
  • 47