![]() |
VOOZH | about |
Given a Tuple List sort tuples by maximum element in a tuple.
Input : test_list = [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)]
Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]
Explanation : 19 > 7 = 7 > 2, is order, hence reverse sorted by maximum element.Input : test_list = [(4, 5, 5, 7), (19, 4, 5, 3), (1, 2)]
Output : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 2)]
Explanation : 19 > 7 > 2, is order, hence reverse sorted by maximum element.
Method #1 : Using max() + sort()
In this, we perform task of getting maximum element in tuple using max(), and sort() operation is used to perform sort.
Output:
The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]
Time Complexity: O(n*nlogn) where n is the number of elements in the list “test_list”. max() + sort() performs n*nlogn number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #2 : Using sort() + lambda + reverse
In this, we use similar functionality, the only difference here being use of lambda fnc. rather than external function for task of getting reverse sorting.
Output:
The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]
Method #3: Using a loop to find the maximum element and sort based on it
The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]
Time complexity: O(nlogn) - sorting takes O(nlogn) time, and the loop takes O(n) time, where n is the length of the input list.
Auxiliary space: O(n) - we are creating a new list with n tuples.
Method #6: Using Heapq module
Step-by-step approach:
The original list is : [(4, 5, 5, 7), (1, 3, 7, 4), (19, 4, 5, 3), (1, 2)] Sorted Tuples : [(19, 4, 5, 3), (4, 5, 5, 7), (1, 3, 7, 4), (1, 2)]
Time complexity: O(n log n), where n is the length of the test_list.
Auxiliary space: O(n), where n is the length of the test_list.