Python | Cropped list Minimum
Last Updated :
09 May, 2023
Sometimes, we require to shrink a list by deletion of its certain elements. One of the methods that is employed to perform this particular task is front and rear element deletion and we also desire to find minimum of this list. It is a good utility whose solution can be useful to have. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list slicing + del operator + min() The del operator can be clubbed with the slicing action to delete the front and rear elements from a list to obtain a cropped version of list. The task of finding minimum is found using min().
Python3
test_list = [ 2 , 3 , 5 , 7 , 9 , 10 , 8 , 6 ]
print ("The original list is : " + str (test_list))
K = 2
del test_list[ - K:], test_list[:K]
res = min (test_list)
print ("The cropped list minimum is : " + str (res))
|
Output :
The original list is : [2, 3, 5, 7, 9, 10, 8, 6]
The cropped list minimum is : 5
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(1), constant extra space is required
Method #2 : Using list slicing + min() Above method can be modified and the use of del operator can be omitted to achieve this particular task. We can slice a list in a way that specific number of elements are removed from the list. The task of finding minimum is found using min().
Python3
test_list = [ 2 , 3 , 5 , 7 , 9 , 10 , 8 , 6 ]
print ("The original list is : " + str (test_list))
K = 2
res = min (test_list[K : - K])
print ("The cropped list minimum is : " + str (res))
|
Output :
The original list is : [2, 3, 5, 7, 9, 10, 8, 6]
The cropped list minimum is : 5
Time Complexity: O(n) where n is the number of elements in the test_list. The list slicing + min() is used to perform the task and it takes O(n) time.
Auxiliary Space: O(1) constant additional space needed
Method #3: Using itertools.islice + min()
Approach:
- Import islice from itertools.
- Initialize the test list.
- Initialize indices from where to where we have to crop.
- Use islice method with a test list, starting indices, and ending indices to crop the list.
- Use the min method on the cropped list.
- Print the minimum element from the cropped list.
Python
from itertools import islice
test_list = [ 2 , 3 , 5 , 7 , 9 , 10 , 8 , 6 ]
print ( "The original list is:" , test_list)
i = 2
j = len (test_list) - i
res = min (islice(test_list, i, j))
print ( "The minimum element in the range is:" , res)
|
Output
('The original list is:', [2, 3, 5, 7, 9, 10, 8, 6])
('The minimum element in the range is:', 5)
Time Complexity: O(N) where N is the length of the test_list.
Auxiliary Space: O(M) where M is the length of the new cropped list.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...