Check whether array is subset of another array or not in Python

Check whether array is subset of another array or not

In this program we will  Check whether array is subset of another array or not in Python. A subset is defined as a set whose elements are all members of another set. We will input two arrays and check whether the second array is subset of first array and display accordingly.

  • Example 1:
    • Array 1 -11,13,5,1,7
    • Array 2 -7,5,1
    • All the elements of Array 2 are present in Array 1
    • Array 2 is subset of Array 1
  • Example 2:
    • Array 1 -23,39,51,5,4
    • Array 2 -7,5,9
    • All the elements of Array 2  are not present in Array 1
    • Array 2 is not subset of Array 1

Learn Arrays or disjoint or not using Python

Python code for checking whether an array is a subset of another array or not

Algorithm:

  1. Input two arrays ar1 and ar2
  2.  Initialize count c=0
  3.  Iterate a for loop over the elements of ar2 and check whether elements of array 2 are present in array 1
  4. Increment count if the condition is true
  5. If count is equal to the length of array 2 then display “Array 2 is subset of Array 1”
  6.  otherwise display “Array 2 is not subset of Array 1”

Python Code(using array iteration):

ar1=list(map(int,input(“Enter array 1”).split()))
ar2=list(map(int,input(“Enter array 2”).split()))
c=0
x=len(ar2)
for i in ar2:
    if i in ar1:
        c+=1
if(c==x):
    print(“Array 2 is subset of Array 1”)
else:
    print(“Array 2 is not subset of Array 1”)

Union function:

Let’s see how to check whether array is subset of another array or not using union function in Python.

In general Mathematics we know that a set is said to subset of another set if A U B = A
In set theory, the union of two sets is the set of all elements in the two sets.

  • A={11 13 5 1 7}
  • B={7 5 1}
  • A U B ={11 13 5 1 7}
    Here A U B equals to set A hence B is subset of A

Algorithm:

  • 1. Read array1
  • 2. Read array2
  • 3. Use union function to find one array is subset of another array or not

Python code (using union function)

ar1=set(map(int,input(“Enter array 1 “).split()))
ar2=set(map(int,input(“Enter array 2 “).split()))
if(ar1.union(ar2)==ar1):
    print(“Array 2 is subset of Array 1”)
else:
    print(“Array 2 is not subset of Array 1”)

Output:

Enter array 1 11 13 5 1 7
Enter array 2 7 5 1
Array 2 is subset of Array 1