Find whether arrays or disjoint or not using Python

Find whether arrays are disjoint or not

In this program we will  find whether arrays are disjoint or not using Python.Two arrays are disjoint if they don’t have no element in common.The intersection of two disjoint sets is an empty set.

  • Example 1: Array 1- 1,2,3,4,5 Array 2-6,7,8,9,10
    • The two arrays don’t have elements in common
    • Arrays are disjoint
  • Example 2: Array 1-4,5,3,8,2 Array 2-3,7,4,5,6
    • The two arrays have 3,4,5 elements in common
    • Arrays are not disjoint
Find whether arrays are disjoint or not
what is intersection

What is intersection and disjoint ?

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

Algorithm 1:

  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 4 5
Enter array2 4 5 6 7 8
Not disjoint

Algorithm 2

  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 4 5
Enter array2 6 7 9
disjoint