![]() |
VOOZH | about |
Given a Tuple list, filter tuples that don't contain duplicates.
Input : test_list = [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4, 9), (2, 3, 2)] Output : [(3, 5, 6, 7)] Explanation : Rest all tuples have duplicate values.
Input : test_list = [(3, 5, 6, 7, 7), (3, 2, 4, 3), (9, 4, 9), (2, 3, 2)] Output : [] Explanation : All tuples have duplicate values.
Method #1 : Using loop + set()
In this, all the tuples are iterated, and duplicacy test is done using set(), if the length of the set is the same as the tuple, it doesn't contain a duplicate.
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Method #2: Using list comprehension
This performs a similar task as above, the difference being that this is one-liner and compact.
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Method #3: Without using any builtin methods
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Method #4:Using filter()+set()+map()
Algorithm:
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Time complexity: O(n*m), where n is the number of tuples in the list test_list and m is the maximum length of a tuple in test_list. The time complexity of set() is O(n), so the loop over the tuples dominates the overall time complexity.
Auxiliary Space: O(n), where n is the number of tuples in the list test_list. This is because the size of the output list res is proportional to the number of tuples in the input list.
Method#5: Using the Recursive method
Algorithm:
The original list is : [(3, 5, 6, 7), (3, 2, 4, 3), (9, 4), (2, 3, 2)] Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Time Complexity: O(n^2)
Let n be the length of the input list test_list. In the worst case, all tuples in the list have unique values, so the function needs to examine all n tuples. Each tuple has a length that is at most n, so computing the set of values for each tuple takes time O(n). Therefore, the time complexity of the function is O(n^2).
Auxiliary Space: O(n)
The space complexity of the function is O(n), which is the maximum depth of the recursion stack. This is because each recursive call adds a new frame to the stack, which contains only the variables first and rest.
Method #6: Using dictionary comprehension
we can create a dictionary comprehension where the keys are the tuples themselves and the values are the number of unique elements in the tuple. Then, you can filter the dictionary to only include tuples with the same number of unique elements as the length of the tuple itself.
Filtered tuples : [(3, 5, 6, 7), (9, 4)]
Time complexity: O(n), where n is the number of tuples in the input list.
Auxiliary space: O(n), since we are creating a dictionary with n key-value pairs.