Python – Check Whether One Array is a Subset of Another Array
In data structures and algorithms, checking if one array is a subset of another is a common problem. In Python, this task can be easily accomplished using built-in data types and methods.
This tutorial will explain the problem, provide sample input and output, outline solution steps, and Python program.
Problem Statement
Given two arrays, array1
and array2
, determine whether all the elements of array2
are present in array1
. In other words, check if array2
is a subset of array1
.
Sample Input and Output
Example 1:
# Input arrays
array1 = [1, 2, 3, 4, 5]
array2 = [2, 3, 5]
# Expected Output: True (array2 is a subset of array1)
Example 2:
# Input arrays
array1 = [1, 2, 3]
array2 = [1, 2, 4]
# Expected Output: False (array2 is not a subset of array1)
Solution Approach
There are several ways to determine if one array is a subset of another in Python. Here are two common methods:
Using Sets: Convert both arrays to sets and use theissubset()
method or the subset operator (<=
). This is efficient and concise.
Using Loop and Membership Check: Iterate through the elements of the potential subset and check if each element exists in the larger array.
Python Program
Method 1: Using Sets
This method converts the arrays into sets and checks if the second set is a subset of the first. It is both concise and efficient.
# Function to check if array2 is a subset of array1 using sets
def is_subset_set(array1, array2):
return set(array2).issubset(set(array1))
# Test Example 1
array1 = [1, 2, 3, 4, 5]
array2 = [2, 3, 5]
print("Is array2 a subset of array1?", is_subset_set(array1, array2)) # Output: True
Method 2: Using Loop and Membership Check
This method iterates through each element of array2
and checks if it exists in array1
. It is useful for understanding the underlying logic.
# Function to check if array2 is a subset of array1 using a loop
def is_subset_loop(array1, array2):
for element in array2:
if element not in array1:
return False
return True
# Test Example 2
array1 = [1, 2, 3]
array2 = [1, 2, 4]
print("Is array2 a subset of array1?", is_subset_loop(array1, array2)) # Output: False
Conclusion
We explored two methods to check if one array is a subset of another in Python:
- Using Sets: A concise and efficient approach using the built-in
issubset()
method. - Using a Loop: A more explicit method that checks membership for each element.
For most cases, using sets is recommended due to its simplicity and speed.