![]() |
VOOZH | about |
Given a Tuple list, filter tuples that are made from consecutive elements, i.e diff is 1.
Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 4), (6, 4, 6, 3)]
Output : [(3, 4, 5, 6)]
Explanation : Only 1 tuple adheres to condition.Input : test_list = [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)]
Output : [(3, 4, 5, 6), (1, 2, 3)]
Explanation : Only 2 tuples adhere to condition.
Method #1: Using loop
In this, for each tuple, we call consecutive elements utility which returns True if tuple is consecutive.
The original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)] The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
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 list comprehension
In this, we perform a similar function as above, just in one-liner shorthand using list comprehension.
The original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)] The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Method #3 : Using min(),max() and range() methods
The original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)] The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Method #4: Using the set() function.
Here are the steps:
The original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)] The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Time complexity: O(n*k), where n is the number of tuples in the input list and k is the length of the longest tuple.
Auxiliary space: O(k) to store the sets s and expected.
Method #5: Using lambda function and filter() function with slicing
Step by step algorithm:
The original list is : [(3, 4, 5, 6), (5, 6, 7, 2), (1, 2, 3), (6, 4, 6, 3)] The filtered tuples : [(3, 4, 5, 6), (1, 2, 3)]
Time Complexity: O(nm), where n is the length of the input list and m is the maximum length of a tuple in the list.
Space Complexity: O(n),where n is the length of the input list.