Skip to content
Related Articles
Python program to Check all strings are mutually disjoint
• Last Updated : 21 Apr, 2021

Given a string list, our task is to write a Python Program to check all strings are disjoint from one another.

Example:

Input : test_list = [“gfg”, “is”, “bet”]

Output : True

Explanation : No string character repeat in other strings.

Input : test_list = [“gfg”, “is”, “best”]

Output : False

Explanation : s repeats in both “is” and “best”, hence false.

Method #1 : Using any() + intersection() + enumerate()

In this, we perform the task of getting common elements using intersection(), and the intersection is performed between all combinations of strings with each other using enumerate() and any() is used to test if any string has any character present in other string.

## Python3

 `# Python3 code to demonstrate working of``# Test if all strings are mutually disjoint``# Using any() + intersection() + enumerate()`` ` `# initializing list``test_list ``=` `[``"gfg"``, ``"is"``, ``"bet"``]`` ` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))`` ` `# performing intersection of each string with every other``res ``=` `not` `any``(``set``(``list``(sub1)).intersection(``set``(``list``(sub2)))``              ``for` `idx, sub1 ``in` `enumerate``(test_list) ``              ``for` `sub2 ``in` `test_list[idx ``+` `1``:])`` ` `# printing result``print``(``"Are strings mutually disjoint? : "` `+` `str``(res))`

Output:

```The original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : True```

Method #2 : Using join() + len() + set()

This problem can be solved by matching the concatenated string lengths and checking for equality of lengths of strings and converted set. Fails in case in which is similar string contains duplicate elements.

## Python3

 `# Python3 code to demonstrate working of``# Test if all strings are mutually disjoint``# Using `` ` `# initializing list``test_list ``=` `[``"gfg"``, ``"is"``, ``"bet"``]``              ` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))`` ` `# performing concatenation and checking ``# for lengths ``concats ``=` `''.join(test_list) ``res ``=` `len``(concats) ``=``=` `len``(``set``(concats))`` ` `# printing result``print``(``"Are strings mutually disjoint? : "` `+` `str``(res))`

Output:

```The original list is : ['gfg', 'is', 'bet']
Are strings mutually disjoint? : False```

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up