Given the Tuple list, trim each tuple by K.
Input : test_list = [(5, 3, 2, 1, 4), (3, 4, 9, 2, 1), (9, 1, 2, 3, 5), (4, 8, 2, 1, 7)], K = 2
Output : [(2,), (9,), (2,), (2,)]
Explanation : 2 elements each from front and rear are removed.
Input : test_list = [(5, 3, 2, 1, 4), (3, 4, 9, 2, 1), (9, 1, 2, 3, 5), (4, 8, 2, 1, 7)], K = 1
Output : [(3, 2, 1), (4, 9, 2), (1, 2, 3), (8, 2, 1)]
Explanation : 1 element each from front and rear are removed.
In this, we omit front and rear K elements by using slicing, converting tuple to list, then reconversion to the tuple.
The original list is : [(5, 3, 2, 1, 4), (3, 4, 9, 2, 1), (9, 1, 2, 3, 5), (4, 8, 2, 1, 7)] Converted Tuples : [(2,), (9,), (2,), (2,)]
In this, we perform tasks in a similar way as the above method, difference being list comprehension is employed to perform the task in one-liner.
The original list is : [(5, 3, 2, 1, 4), (3, 4, 9, 2, 1), (9, 1, 2, 3, 5), (4, 8, 2, 1, 7)] Converted Tuples : [(2,), (9,), (2,), (2,)]
Time Complexity: O(n), where n is the length of the input list. This is because we’re using the built-inlist comprehension + slicing which all has a time complexity of O(nlogn) in the worst case.
Auxiliary Space: O(n), as we’re using additional space other than the input list itself.