[Tutor] A program that can check if all elements of the list are mutually disjoint

Peter Otten __peter__ at web.de
Sun Jun 6 05:20:22 EDT 2021


On 06/06/2021 10:48, Manprit Singh wrote:
> Dear sir ,
> 
> But now i have one more question :
> If you can see  in the last mails :
> The function posted by Roel  is :
> def are_elements_disjoint(seq):
>       sets = (set(elem) for elem in seq)
>       pairs = combinations(sets, 2)
>       return all(a.isdisjoint(b) for (a, b) in pairs)
> 
> If you notice he is making an iterator "sets" of all elements of the seq in
> the starting
> 
> Now coming to  the function made by me :
> 
> import itertools
> def is_mutually_disjoint(arr):
>      comb = itertools.combinations(lst, 2)
>      return all(set(ele1).isdisjoint(ele2) for ele1, ele2 in comb)
> 
> in my function i am making set inside all() function. So what is the right
> & efficient approach ?

set_a.isdisjoint(set_b) is probably a tad faster than 
set_a.isdisjoint(string_b), so it makes sense to convert the strings 
before doing the check, especially since the set is needed anyway.

In the following pathological case the difference is three orders of 
magnitude:

PS C:\> py -m timeit -s "s = set('a'); t = 'b'*10000" "s.isdisjoint(t)"
500 loops, best of 5: 719 usec per loop
PS C:\> py -m timeit -s "s = set('a'); t = set('b'*10000)" "s.isdisjoint(t)"
1000000 loops, best of 5: 305 nsec per loop



More information about the Tutor mailing list