Find whether an array is subset of another array in Python

In this article, we will find whether an array is a subset of another array in Python. So, we have to see whether the array is the subset of another array or not. Now, what is subarray or which arrays are called as subarray?

What is a Subset of an Array?

The array A is called the subset of another array B when all the elements of the array A are present in the array B and also the length of A must be less than or equal to the length of B.

Example:

Let’s take an example. A is an array consists of the elements [2,4,6,9,1,5]. The array B has elements like [2,3,6]. Now, can we say B is the subset of A?

No, we cannot define it that. Because the element is 3 is not present in the array A. So, here we have easily proved that array B is not the subset of array A.

Now, let’s go through another example. A is an array with elements [1,2,5,9,8,7]. The array B is [1,1,2,5,8,7,9]. Now, can we say B is the subset of A?

No, Because the length of B is greater than the length of array A. So, we cannot tell this as a subset of the array.

Program Code:

Look at the Python code given below where we find if an array is a subset of another array or not:

import numpy as np

n=int(input("Enter the length of the array: "))
a=[]
for i in range(n):
    a.append(int(input("Elements: ")))
a=np.array(a)

m=int(input("Enter the length of the subarray: "))
b=[]
for _ in range(m):
    b.append(int(input("Elements: ")))
b=np.array(b)

if m>n:
    print("Not Sub Array")
else:
    count=0
    for i in b:
        for j in a:
            if i==j:
                count+=1
    if count==m:
        print("Subarray")
    else:
        print("Not sub array")

OUTPUT:

Enter the length of the array: 4
Elements: 12
Elements: 5
Elements: 3
Elements: 69
Enter the length of the subarray: 2
Elements: 69
Elements: 3
Subarray

Explanation:

Here, we have taken the length of the array as 4. Therefore, we have inserted all the elements one by one. Then we put the length of the sub-array. Please notice carefully that we have taken the length less than the length of the actual array. Either we take greater value, it will respond as not sub-array. After that, we have entered the elements and checked whether all are present in the main array. Then we have concluded that it is the subset of the previous array.

You can also go through these articles.

Leave a Reply

Your email address will not be published. Required fields are marked *