Finding Arrays are disjoint or not

disjoint set or not in python

Arrays are disjoint or not in Python

In this article we will see a program of Finding Arrays are disjoint or not. We will take two arrays from user. Disjoint array are those array where no elements are common between two sets. If even one element is common between two array then the given array is not disjoint. Let’s see an example
  • Array 1: 1,2,3,4
  • Array 2: 7,8.9,10
The above two arrays are disjoint because they have nothing common between them. First we will understand what is disjoint then we will see two methods of Finding Arrays are disjoint or not.

Intersection in Python

Intersection is denoted by a symbol “∩” which when applied between two sets gives the common elements in the both sets/arrays. In python we can use either intersection( ) function or “&” symbol between two sets to find intersection.

set1= {1,2,3,4}  and  set2={5,6,7,8}
intersection of set1 and set2 is = { } . So this is disjoint.

set1 ={1,2,3,4}  and  set2={4,5,6,7}

intersection of set1 and set2 = {4} . So this is not disjoint

disjoint set or not in python

Method 1

Algorithm:

  1. Input two arrays and pass them as arguments to a function
  2. In the body of function initialize a nested for loop
  3. Traverse the array 1 using the outer loop.Find whether arrays are disjoint or not using Python
  4. Use the inner loop to check if the elements in array 2 are found in array 1.
  5. If at least one element of array 2 is found in array 1, return False otherwise return True.
  6.  If function returns True display “Disjoint”,otherwise “Not disjoint”
 

Python code:

def fun(l1,l2):
    for i in range(0,len(l1)):
        for j in range(0,len(l2)):
            if(l1[i]==l2[j]):
                return False
    return True
l1=list(map(int,input("Enter array1: ").split()))
l2=list(map(int,input("Enter array2: ").split()))
if(fun(l1,l2)):
    print("Disjoint")
else:
    print("Not disjoint")

Output

Enter array1: 1 2 3
Enter array2: 4 5 6
Disjoint

    Method 2

Algorithm:

  1.  Read 1st array as set using set() function
  2. Read 2nd array as set using set() function
  3. By using intersection function in sets we can find whether there is any common element present in both sets or not
  4. If intersection is empty then it is disjoint , else if it has at least one element it is not a disjoint

Python code:

l1=set(map(int,input("Enter array1: ").split()))
l2=set(map(int,input("Enter array2: ").split()))
if(l1.intersection(l2)):
    print("Not a disjoint")
else:
    print("disjoint")

Output

Enter array1: 1 2 3
Enter array2: 1 2 4
Not a disjoint