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

Peter Otten __peter__ at web.de
Sat Jun 5 10:58:58 EDT 2021


On 05/06/2021 15:09, Manprit Singh 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.
> 

>  First of all need
> to know if it is correct or not, if it is correct ,

I'm sure you can find that out yourself, or get some confidence at least.

First of all you have to tighten your definition; how does "having 
anything in common" translate into code?

Then turn your algorithm into a function, preferably one with a result 
rather than print() calls. Then write a few tests (unittest or doctest) 
that call your function with various arguments that cover what you 
expect your function to handle. Example:

def disjoint_words(words):
     """
     >>> disjoint_words(["amba", "Joy", "Preet"])
     True
     """
     return True

 > I have written the code but it seems quite unreadable.

I'd say that my alternative is *very* readable -- but also wrong.
Write test cases to bring that to light, then fix the function.
Let's assume you do this by reusing the code you posted. The function 
may now be uglier, but hopefully correct. The print() calls are gone. 
You can be confident that the code only depends on the 'words' argument 
and has no hidden interactions with the rest of your script.
That's progress ;)

Because you have tests in place you can now refactor without fear. If a 
test continues to fail just go back to your previous working version of 
the function.
Hooray to version control ;)

What would be possible approaches to improve your code?
The low-hanging fruit: factor out the two nested for loops (I'd look 
into itertools for that).

A bit more demanding: see what you can do about the algorithm. Is there 
a chance to replace O(something) with O(something else)?

I need to know if this
> can be done in a better way or not. 

Yes ;)

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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 




More information about the Tutor mailing list