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

Roel Schroeven roel at roelschroeven.net
Sat Jun 5 13:28:03 EDT 2021


Manprit Singh schreef op 5/06/2021 om 15:09:
> 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")
> 

Looks correct to me, at first sight. As Peter Otten mentioned, the best 
way to find out is to construct a number of test cases and a program to 
run those for you. Maybe have a look at a unit testing framework.

I'm a big fan of putting code like that in a function. Then you can 
reason about what the function does independently from the rest of the 
program.

I also think it's a good idea to split off the code to generate all the 
pairs of words in a separate function. Luckily there already is a 
function that does just that: itertools.combination().

Lastly I think it's better to create the sets (that you eventually use 
with disjoint) only once, instead of every time again. That does imply 
more memory usage since all sets are in memory at the same time, so 
maybe there are situations where it's better not to do this.

This is what I came up with:

from itertools import combinations

ls = ["amba", "Joy", "Preet"]

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 are_elements_disjoint(ls):
     print('Mutually disjoint')
else:
     print('Not mutually disjoint')


-- 
"Honest criticism is hard to take, particularly from a relative, a
friend, an acquaintance, or a stranger."
         -- Franklin P. Jones

Roel Schroeven



More information about the Tutor mailing list