Python – Trim tuples by K
Given the Tuple list, trim each tuple by K.
Examples:
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.
Method #1: Using loop + slicing
In this, we omit front and rear K elements by using slicing, converting tuple to list, then reconversion to the tuple.
Python3
test_list = [( 5 , 3 , 2 , 1 , 4 ), ( 3 , 4 , 9 , 2 , 1 ),
( 9 , 1 , 2 , 3 , 5 ), ( 4 , 8 , 2 , 1 , 7 )]
print ( "The original list is : " + str (test_list))
K = 2
res = []
for ele in test_list:
N = len (ele)
res.append( tuple ( list (ele)[K: N - K]))
print ( "Converted Tuples : " + str (res))
|
Output:
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)
Auxiliary Space: O(n)
Method #2: Using list comprehension + slicing
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.
Python3
test_list = [( 5 , 3 , 2 , 1 , 4 ), ( 3 , 4 , 9 , 2 , 1 ),
( 9 , 1 , 2 , 3 , 5 ), ( 4 , 8 , 2 , 1 , 7 )]
print ( "The original list is : " + str (test_list))
K = 2
res = [ tuple ( list (ele)[K: len (ele) - K]) for ele in test_list]
print ( "Converted Tuples : " + str (res))
|
Output:
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.
Last Updated :
08 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...