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

Manprit Singh manpritsinghece at gmail.com
Sun Jun 6 04:48:35 EDT 2021


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 ?

Regards
Manprit Singh



On Sat, Jun 5, 2021 at 6:39 PM Manprit Singh <manpritsinghece at gmail.com>
wrote:

> Dear sir,
> Consider a list :
> ls = ["amba", "Joy", "Preet"]
>
> The elements of the list are mutually disjoint, as no two elements of the
> list have anything in common.
>
> I have written the code but it seems quite unreadable.  First of all need
> to know if it is correct or not, if it is correct , I need to know if this
> can be done in a better way or not. Kindly have a look at below given code :
>
> ls = ["amba", "Joy", "Preet"]
> for idx, ele in enumerate(ls):
>     if idx < len(ls)-1:
>         if not all(set(ele).isdisjoint(ch)for ch in ls[idx+1:]):
>             print("Not mutually disjoint")
>             break
> else:
>     print("Mutually disjoint")
>
> Regards
> Manprit Singh
>


More information about the Tutor mailing list