[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:19:30 EDT 2021


Dear sir ,
Thanks to Roel . Finally today I have understood the importance of standard
library modules, I work with mostly numbers when programming , and feel
that itertools is very very useful.
The solution that i do agree is as follows and seems readable to me too:

import itertools
def is_mutually_disjoint(arr):
    comb = itertools.combinations(lst, 2)
    return all(set(ele1).isdisjoint(ele2) for ele1, ele2 in comb)

lst = ["amar", "sit", "xyz", "kla"]
ans = is_mutually_disjoint(lst)
print(ans)      - gives o/p as False that means the elements of list lst
are not mutually disjoint. (amar and kla have "a"  as common character)

and

lst = ["amar", "sit", "xyz", "klg"]
ans = is_mutually_disjoint(lst)
print(ans)   - gives True as now in the list there are no two elements
which have anything in common, so the elements of list are mutually disjoint

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