Open In App

Python – Matrix Row subset

Last Updated : 09 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python Matrix, one can have a problem in which, one needs to extract all the rows that are a possible subset of any row of other Matrix. This kind of problem can have applications in data domains as a matrix is a key data type in those domains. Let’s discuss certain ways in which this problem can be solved.

Input : test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 6]], check_matr = [[2, 3], [1, 2], [9, 0]] 
Output : [[2, 3]] 
Input : test_list = [[4, 1, 2], [2, 3, 4], [9, 8, 0]], check_matr = [[2, 3], [1, 2], [9, 0]] 
Output : [[2, 3], [1, 2], [9, 0]]

Method #1: Using any() + all() + list comprehension

The combination of the above functions offers a way in which this problem can be solved. In this, we check for the occurrence of all elements of row using all(), and any() is used to match any row of the Matrix. List comprehension is used to bind the logic together. 

Python3




# Python3 code to demonstrate working of
# Matrix Row subset using
# any() + all() + list comprehension
 
# initializing lists
test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing check Matrix
check_matr = [[2, 3], [1, 2], [9, 0]]
 
# Matrix Row subset
# Using any() + all() + list comprehension
res = [ele for ele in check_matr
       if any(all(a in sub for a in ele)
              for sub in test_list)]
 
# printing result
print("Matrix row subsets : " + str(res))


Output : 

The original list is : [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
Matrix row subsets : [[2, 3], [9, 0]]

Time complexity: O(n^3) where n is the size of the input matrix. This is because the program uses nested loops to iterate over the elements of the input matrix and the check matrix, and the all() and any() functions also iterate over the lists. Therefore, the time complexity of the program can be expressed as O(n * m * k), where n is the number of rows in the check matrix, m is the number of rows in the input matrix, and k is the number of elements in each row.

Auxiliary space: O(n), where n is the size of the input matrix. This is because the program creates a new list res to store the matrix row subsets. The size of this list is at most equal to the number of rows in the input matrix. Therefore, the space complexity of the program can be expressed as O(m), where m is the number of rows in the input matrix.

Method #2: Using product() + set() + list comprehension

The combination of the above functions can be used for this task. In this, we perform the task of nested loop using product() and set() conversion to check for subset of one container over another. List comprehension is used to bind all together. 

Python3




# Python3 code to demonstrate working of
# Matrix Row subset
# Using product() + set() + list comprehension
import itertools
 
# initializing lists
test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing check Matrix
check_matr = [[2, 3], [1, 2], [9, 0]]
 
# Matrix Row subset
# Using product() + set() + list comprehension
res = [a for a, b in itertools.product(check_matr, test_list)
                                         if set(a) <= set(b)]
 
# printing result
print("Matrix row subsets : " + str(res))


Output : 

The original list is : [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
Matrix row subsets : [[2, 3], [9, 0]]

Time complexity: O(n^2 * m^2), where n is the number of rows in check_matr and m is the number of rows in test_list.
Auxiliary space: O(m), where m is the number of elements in the longest row of test_list. 

Method 3: Using nested loops and set intersection to find the row subsets

In this code loops over each row in check_matr and each list in test_list, then checks if the set of the current row is a subset of the set of the current list using set.issubset(). If it is, the row is added to the result list.

Python3




test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
check_matr = [[2, 3], [1, 2], [9, 0]]
 
res = []
for row in check_matr:
    for lst in test_list:
        if set(row).issubset(set(lst)):
            res.append(row)
 
print("Matrix row subsets: ", res)


Output

Matrix row subsets:  [[2, 3], [9, 0]]

Time Complexity: O(n * m * k) where n, m, and k are the lengths of check_matr, test_list.
Auxiliary Space: O(1) since it uses a constant amount of extra space to store variables like res, row, and lst.

Method #4: Using map() and set operations

  1. Initialize the lists:
  2. Define a function is_subset(a, b) that takes two lists as arguments and returns True if a is a subset of b, False otherwise:
  3. Use map() to apply the function to each pair of sublists from check_matr and test_list:
  4. Print the result:

Python3




test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
check_matr = [[2, 3], [1, 2], [9, 0]]
def is_subset(a, b):
    return set(a).issubset(set(b))
res = [list(a) for a in check_matr if any(map(lambda b: is_subset(a, b), test_list))]
print("Matrix row subsets : " + str(res))


Output

Matrix row subsets : [[2, 3], [9, 0]]

Time complexity: O(nmk) where n is the length of test_list, m is the length of check_matr, and k is the length of the sublists.
Auxiliary space: O(1) since we are not storing any additional data structures.

Method #5: Using set comprehension and issubset() method

  1. Initialize an empty list res to store the row subsets.
  2. Iterate through each row a in check_matr.
  3. Using set comprehension, create a set set_a from the elements of a.
  4. Iterate through each row b in test_list.
  5. Using set comprehension, create a set set_b from the elements of b.
  6. Check if set_a is a subset of set_b using the issubset() method.
  7. If set_a is a subset of set_b, append a to the res list.
  8. Print the res list.

Python3




# Python3 code to demonstrate working of
# Matrix Row subset using
# set comprehension and issubset() method
 
# Initializing lists
test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# Initializing check Matrix
check_matr = [[2, 3], [1, 2], [9, 0]]
 
# Matrix Row subset
# using set comprehension and issubset() method
res = []
for a in check_matr:
 
    # Set A
    set_a = {elem for elem in a}
    for b in test_list:
 
        # Set B
        set_b = {elem for elem in b}
        if set_a.issubset(set_b):
            res.append(a)
 
# Printing result
print("Matrix row subsets : " + str(res))


Output

The original list is : [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
Matrix row subsets : [[2, 3], [9, 0]]

Time complexity: O(nmk) where n is the number of rows in check_matr, m is the number of rows in test_list, and k is the length of each row.
Auxiliary space: O(k) where k is the length of each row.

Method 6: Use the built-in function filter() along with a lambda function 

  1. Create two matrices test_list and check_matr containing integer values.
  2. Define a lambda function is_subset that takes a row from check_matr and returns True if it is a subset of any row in test_list.
  3. Create a list res to store the rows of check_matr that are subsets of test_list.
  4. Use the filter() function to apply the is_subset function to each row in check_matr.
  5. Convert the filtered result into a list and store it in res.
  6. Print the resulting list res to show the rows of check_matr that are subsets of test_list.

Python3




test_list = [[4, 5, 7], [2, 3, 4], [9, 8, 0]]
check_matr = [[2, 3], [1, 2], [9, 0]]
 
is_subset = lambda row: any(set(row).issubset(set(lst)) for lst in test_list)
res = list(filter(is_subset, check_matr))
 
print("Matrix row subsets: ", res)


Output

Matrix row subsets:  [[2, 3], [9, 0]]

Time complexity: O(n^2), where n is the number of elements in the input matrices
Auxiliary space: O(1), because it does not use any additional data structures besides the input matrices and the output list.



Previous Article
Next Article

Similar Reads

SymPy | Subset.subset() in Python
Subset.subset() : subset() is a sympy Python library function that returns the subset represented by the current instance. Syntax : sympy.combinatorics.subset.Subset.subset() Return : the subset represented by the current instance. Code #1 : subset() Example # Python code explaining # SymPy.Subset.subset() # importing SymPy libraries from sympy.com
1 min read
Python - Incremental K sized Row Matrix Initialization
Sometimes, while working with Python, we can have a problem in which we need to perform initialization of matrix with Incremental numbers. This kind of application can come in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + list slicing This task can be performed in brute way using loop.
6 min read
Python | Remove False row from matrix
Sometimes, while handling data, especially in the Machine Learning domain, we need to go through a lot of incomplete or empty data. We sometimes need to eliminate the rows which do not contain a value in any of the columns. Let's discuss certain ways to remove the rows that have all False values as list columns. Method #1 : Using list comprehension
9 min read
Python | Row lengths in Matrix
The problems concerning matrix are quite common in both competitive programming and Data Science domain. One such problem that we might face is of finding the lengths of rows of matrix in uneven sized matrix. Let's discuss certain ways in which this problem can be solved. Method #1 : Using max() + map() + sum() + list comprehension The combination
4 min read
Python | sympy.Matrix.row() method
With the help of sympy.Matrix.row() method, we can extract the rows of the matrix. Syntax : sympy.Matrix.row() Return : Return the row of a matrix. Example #1 : In the given example we can see that the sympy.Matrix().row() method is used to extract the rows of a matrix. # Import all the methods from sympy from sympy import * # use the row() method
1 min read
Python - Consecutive Row summation in Matrix
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the sum between the like indices when compared with the next list. The sum between the like elements in that index is returned. Let’s discuss certain ways in which this task can be performed. Method #1 : Using sum()
5 min read
Python | Remove last element from each row in Matrix
Sometimes, while working with Matrix data, we can have a stray element attached at rear end of each row of matrix. This can be undesired at times and wished to be removed. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + del + list slicing The combination of the above functionalities can be used to perform thi
6 min read
Python - Row with Minimum Sum in Matrix
We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambda The above two function can help us achieving this part
4 min read
Python | Row with Minimum element in Matrix
We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but sometimes we need to print the entire row containing it and having shorthands to perform the same are always helpful as this kind of problem can come in web development. Let's discuss certain ways in
5 min read
Python | Reverse Sort Row Matrix integration
Often during problem solving we come across to many problems where we need to reverse sort the list. But sometimes we would also want to reverse sort another list so that the elements of are automatically shifted and remain at same index as the first list even after first list get reverse sorted. Let’s discuss certain ways in which this can be done
7 min read