Python – Custom Lower bound a List
Last Updated :
08 Mar, 2023
Given a list, assign a custom lower-bound value to it.
Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 3
Output : [5, 7, 8, 3, 3, 5, 3]
Explanation : All elements less than 3, assigned 3.
Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 5
Output : [5, 7, 8, 5, 5, 5, 5]
Explanation : All elements less than 5, assigned 5.
Method #1: Using list comprehension
In this, we check for each element if it’s lower than lower-bound, if yes, then assign the decided lower-bound to that element.
Python3
test_list = [ 5 , 7 , 8 , 2 , 3 , 5 , 1 ]
print ( "The original list is : " + str (test_list))
K = 4
res = [ele if ele > = K else K for ele in test_list]
print ( "List with Lowerbounds : " + str (res))
|
Output
The original list is : [5, 7, 8, 2, 3, 5, 1]
List with Lowerbounds : [5, 7, 8, 4, 4, 5, 4]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using list comprehension + max()
In this, we perform comparison using max(), assign max of the element, or the lower-bound as decided.
Python3
test_list = [ 5 , 7 , 8 , 2 , 3 , 5 , 1 ]
print ( "The original list is : " + str (test_list))
K = 4
res = [ max (ele, K) for ele in test_list]
print ( "List with Lowerbounds : " + str (res))
|
Output
The original list is : [5, 7, 8, 2, 3, 5, 1]
List with Lowerbounds : [5, 7, 8, 4, 4, 5, 4]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. This is because we’re using the built-in list comprehension + max() which all has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), no extra space is required
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...