Introduction

In computer science, disjoint sets are a common data structure used to solve problems involving partitioning a set or grouping objects based on certain criteria. This powerful tool can be used to efficiently organize and manipulate data, and is especially useful in algorithms that involve connected components and graph theory. In this Python tutorial, we will go over the basics of Disjoint Sets and how to implement them in Python. 

Disjoint Sets :

  • If there are no common elements in two sets then they are called disjoint sets.
  • The intersection of disjoint sets is an empty set. 
  • In Python we can find if two sets are disjoint by using  isdisjoint()  method.
  • The basic syntax of using a isdisjoint() method is :   bool_value = set_1.issuperset(set_2) 
  • The  isdisjoint()  method returns a boolean value :
    • True if  set_1  and  set_2  are disjoint.
    • False if  set_1  and  set_2  are not disjoint.
  • The  isdisjoint()  method can also accept iterable objects as arguments.
  • The  isdisjoint()  method converts the iterable object into set before checking if the two sets are disjoint.
  • Code Sample : 

set_1 = {1, 2, 3}
set_2 = {4, 5, 6, 7}
val = set_1.isdisjoint(set_2)

print(f"Value of set_1 = {set_1}")
print(f"Value of set_2 = {set_2}")
print(f"set_1 and set_2 are disjoint = {val}")

# Output
# Value of set_1 = {1, 2, 3}
# Value of set_2 = {4, 5, 6, 7}
# set_1 and set_2 are disjoint = True


 

Prev. Tutorial : Supersets

Next Tutorial : Set comprehension