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)
{1,2,3}.isdisjoint({4,5,6})
will return true since there is no intersection.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With