Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python isDisjoint() runtime

What is the algorithmic runtime of Python 2.7's isDisjoint(other) method for sets? Is it faster than simply doing intersection(other) and then checking len()>0 of that returned intersection?

like image 722
frozen Avatar asked Nov 01 '25 00:11

frozen


1 Answers

The complexity in both cases is going to be O(min(len(s), len(t)). The only difference is that intersection creates a new set of all matched items and isdisjoint simply returns a boolean and can short-circuit as soon as a match is found.

Example that short-circuits right away:

>>> s1 = set(range(10**6))
>>> s2 = set([0] + list(range((10**6), 2 * (10**6))))
>>> s1.intersection(s2)
set([0])
>>> %timeit s1.isdisjoint(s2)
10000000 loops, best of 3: 94.5 ns per loop
>>> %timeit s1.intersection(s2)
100 loops, best of 3: 6.82 ms per loop

In this case the timings are close to each other, suggesting the matched item was found pretty late during the loop.

>>> s1 = set(range(10**6))
>>> s2 = set(range((10**6) - 1, 2 * (10**6)))
>>> s1.intersection(s2)
set([999999])
>>> %timeit s1.isdisjoint(s2)
100 loops, best of 3: 5.37 ms per loop
>>> %timeit s1.intersection(s2)
100 loops, best of 3: 6.62 ms per loop
like image 57
Ashwini Chaudhary Avatar answered Nov 03 '25 13:11

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!