For example:
a=[-5,-3,-1,1,3,5]
I want to find a negative and a positive minimum.
example: negative
print(min(a)) = -5
positive
print(min(a)) = 1
The Python min() function returns the lowest value in a list of items. min() can be used to find the smallest number in a list or first string that would appear in the list if the list were ordered alphabetically.
Python min() Function The min() function returns the item with the lowest value, or the item with the lowest value in an iterable. If the values are strings, an alphabetically comparison is done.
Process: Initially assign the element located at 0 to min using min = l[0]. using for loop visit each location serially from 1 to len(l)-1. if the element located in any position is lesser than min, then assign the element as min by using min = l[i] finally min holds the minimum value in the list.
For getting minimum negative:
min(a)
For getting minimum positive:
min(filter(lambda x:x>0,a))
>>> a = [-5,-3,-1,1,3,5]
>>> min(el for el in a if el < 0)
-5
>>> min(el for el in a if el > 0)
1
Special handling may be required if a
doesn't contain any negative or any positive values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With