Given a Matrix, filter rows with required elements from other list.
Input : test_list = [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]], check_list = [4, 6, 2, 8]
Output : [[2, 4, 6], [2, 4, 8]]
Explanation : All elements are from the check list.
Input : test_list = [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]], check_list = [6, 2, 8]
Output : []
Explanation : No list with all elements from check list.
In this, we perform iteration and filtering using list comprehension from list and check for all elements present in each row using all().
The original list is : [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]] Filtered rows : [[2, 4, 6], [2, 4, 8]]
In this, the task of filtering is done using filter() and lambda, all() is used for the task of extracting all elements from that are present in the checklist.
The original list is : [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]] Filtered rows : [[2, 4, 6], [2, 4, 8]]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. filter() + lambda + all() performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
OutputThe original list is : [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]]
Filtered rows : [[2, 4, 6], [2, 4, 8]]
1.Initialize the given list and check list.
2.Convert the check list into set for efficient subset operation.
3.Loop through each sub-list of the given list.
4.Check if the set formed by the sub-list is a subset of the check set.
5.If yes, append the sub-list to the result list.
6.Return the result list.
OutputThe original list is : [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]]
Filtered rows : [[2, 4, 6], [2, 4, 8]]
Initialize an empty list called res.
Iterate over each sublist in test_list using a for loop.
Initialize a variable called flag to True.
Iterate over each element in the sublist using another for loop.
If the element is not present in check_list, set the flag to False and break out of the inner for loop.
If the flag is still True after iterating over all elements of the sublist, append the sublist to res.
Print the filtered rows.
OutputFiltered rows : [[2, 4, 6], [2, 4, 8]]
Time complexity: O(N*M) where N is the number of sublists in test_list and M is the maximum length of any sublist.
Auxiliary space: O(K) where K is the number of sublists that are a subset of check_list.