![]() |
VOOZH | about |
Given List of tuples, filter tuples that have same values.
Input : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)]
Output : [(6, 6, 6)]
Explanation : 1 tuple with same elements.Input : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)]
Output : []
Explanation : No tuple with same elements.
Method #1 : Using list comprehension + set() + len()
In this, we check for length of set converted tuple to be 1, if that checks out, tuple is added to result, else, omitted.
The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] Filtered Tuples : [(6, 6, 6), (1, 1)]
Time complexity: O(n), where n is the length of the test_list. The list comprehension + set() + len() takes O(n) time
Auxiliary Space: O(n), extra space of size n is required
Method #2 : Using filter() + lambda + set() + len()
In this, we perform task of filtering using filter(), and single element logic is checked in lambda function using set() and len().
The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] Filtered Tuples : [(6, 6, 6), (1, 1)]
Method #3 : Using count() and len() methods
Approach
The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] Filtered Tuples : [(6, 6, 6), (1, 1)]
Time Complexity : O(N)
Auxiliary Space : O(N)
Method 4 : Using a for loop and a set.
Explanation:
We use a for loop to iterate over the tuples in test_list.
Inside the for loop, we create a set from the current tuple using the set() function. A set is an unordered collection of unique elements, so if all elements in the tuple are the same, the set will contain only one element.
We check the length of the set using the len() function. If the length is 1, it means that all elements in the tuple are the same, so we append the tuple to the new list res.
Finally, we print the filtered tuples.
The original list is : [(5, 6, 5, 5), (6, 6, 6), (1, 1), (9, 10)] Filtered Tuples : [(6, 6, 6), (1, 1)]
This approach has a time complexity of O(n*k), where n is the number of tuples in the list and k is the maximum length of a tuple.
The auxiliary space is O(k), because we create a set for each tuple.