w3resource

Python: Check if two given sets have no elements in common

Python sets: Exercise-17 with Solution

Write a Python program to check if two given sets have no elements in common.

Sample Solution-1:

Python Code:

x = {1,2,3,4}
y = {4,5,6,7}
z = {8}
print("Original set elements:")
print(x)
print(y)
print(z)
print("\nConfirm two given sets have no element(s) in common:")
print("\nCompare x and y:")
print(x.isdisjoint(y))
print("\nCompare x and z:")
print(z.isdisjoint(x))
print("\nCompare y and z:")
print(y.isdisjoint(z))

Sample Output:

Original set elements:
{1, 2, 3, 4}
{4, 5, 6, 7}
{8}

Confirm two given sets have no element(s) in common:

Compare x and y:
False

Compare x and z:
True

Compare y and z:
True

Pictorial Presentation:

Python Sets: Check if two given sets have no elements in common.
Python Sets: Check if two given sets have no elements in common.
Python Sets: Check if two given sets have no elements in common.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Sample Solution-2:

Python Code:

def compare_sets(s1,s2):
    for i in s1:
        if i in s2:
            return False
    return True

x = {1,2,3,4}
y = {4,5,6,7}
z = {8}
print("Original set elements:")
print(x)
print(y)
print(z)
print("\nConfirm two given sets have no element(s) in common:")
print("\nCompare x and y:")
print(compare_sets(x,y))
print("\nCompare x and z:")
print(compare_sets(x,z)) 
print("\nCompare y and z:")
print(compare_sets(y,z))

Sample Output:

Original set elements:
{1, 2, 3, 4}
{4, 5, 6, 7}
{8}

Confirm two given sets have no element(s) in common:

Compare x and y:
False

Compare x and z:
True

Compare y and z:
True

Flowchart:

Flowchart: Check if two given sets have no elements in common.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to check if a given value is present in a set or not.
Next: Write a Python program to check if a given set is superset of itself and superset of another given set.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

While-else construct:

i = 5

while i > 1:
    print("Whil-ing away!")
    i -= 1
    if i == 3:
        break
else:
    print("Finished up!")