![]() |
VOOZH | about |
Given a List of Tuples, extract tuples in which each element is max K.
Input : test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)], K = 7 Output : [(4, 5, 3), (3, 4, 7), (4, 3, 2)] Explanation : All tuples have maximum value 7.
Input : test_list = [(4, 5, 3), (4, 3, 2), (4, 7, 8)], K = 7 Output : [(4, 5, 3), (4, 3, 2)] Explanation : All tuples have maximum value 7.
Method #1 : Using loop
In this, we iterate through all tuple elements, if element found greater than K, then tuple is flagged and not added in result list.
The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)] The filtered tuples : [(4, 5, 3), (4, 3, 2)]
Time Complexity: O(n*n), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using all() + list comprehension
In this, we check for all the elements to be at max K using all(), if yes, then those tuples are added to result.
The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)] The filtered tuples : [(4, 5, 3), (4, 3, 2)]
Method 3 : using filter() method with lambda function.
Steps to solve the problem :
The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)] The filtered tuples : [(4, 5, 3), (4, 3, 2)]
Time complexity: O(n*k), where n is the number of tuples in the list and k is the number of elements in each tuple.
Auxiliary space: O(n), where n is the number of tuples in the list.
Method 4: Using reduce() method from functools module
The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)] The filtered tuples : [(4, 5, 3), (4, 3, 2)]
The time complexity : O(n*m), where n is the length of the input list, and m is the length of the largest tuple in the list.
The auxiliary space complexity : O(n), where n is the length of the input list.