Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum values in a python 3.3 list

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
like image 534
Droid Avatar asked Mar 12 '13 16:03

Droid


People also ask

How do you find the minimum value in a list Python?

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.

What is MIN () function in Python?

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.

How do you find the smallest number in a list in Python without Max?

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.


2 Answers

For getting minimum negative:

min(a)

For getting minimum positive:

min(filter(lambda x:x>0,a))

like image 95
Sibi Avatar answered Sep 18 '22 05:09

Sibi


>>> 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.

like image 23
NPE Avatar answered Sep 17 '22 05:09

NPE