Given a list of tuples, filter by Kth element presence in List.
Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 2
Output : [('is', 4, 3)]
Explanation : 3 is 2nd element and present in list, hence filtered tuple.
Input : test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)], check_list = [4, 2, 3, 10], K = 1
Output : [('is', 4, 3), ('best', 10, 29)]
Explanation : 4 and 10 are 1st elements and present in list, hence filtered tuples.
In this, we check for each element of Tuple's Kth element to be present in list in shorthand using list comprehension and containment is tested using in operator.
OutputThe original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
The filtered tuples : [('is', 4, 3), ('best', 10, 29)]
In this, lambda function checks for element presence and filter performs task of filtering tuples.
OutputThe original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
The filtered tuples : [('is', 4, 3), ('best', 10, 29)]
OutputThe original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
The filtered tuples : [('is', 4, 3), ('best', 10, 29)]
Time Complexity: O(n), where n is the number of tuples in test_list.
Auxiliary Space: O(k), where k is the number of tuples that pass the filter. The space used by the res list.
OutputThe original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
The filtered tuples : [('is', 4, 3), ('best', 10, 29)]
The time complexity of this recursive function is O(n), where n is the number of tuples in the input list. This is because the function visits each tuple in the list once.
The space complexity is also O(n) because the function creates a new list to store the filtered tuples. However, in the worst case where all tuples in the input list are selected, the space complexity can be O(n^2) due to the recursive calls creating new lists.