Finding the Min for positive and negative in python 3.3 list

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Mar 12 21:57:16 EDT 2013


On Tue, 12 Mar 2013 17:03:08 +0000, Norah Jones wrote:

> For example:
> a=[-15,-30,-10,1,3,5]
> 
> I want to find a negative and a positive minimum.
> 
> example: negative
> print(min(a)) = -30
>  
> positive
> print(min(a)) = 1

Thank you for providing examples, but they don't really cover all the 
possibilities. For example, if you had:

a = [-1, -2, -3, 100, 200, 300]

I can see that you consider -3 to be the "negative minimum". Do you 
consider the "positive minimum" to be 100, or 1?

If you expect it to be 100, then the solution is:

    min([item for item in a if item > 0])

If you expect it to be 1, then the solution is:

    min([abs(item) for item in a])

which could also be written as:

    min(map(abs, a))

A third alternative is in Python 3.3:

    min(a, key=abs)

which will return -1.



-- 
Steven



More information about the Python-list mailing list