Droid
Droid

Reputation: 1362

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

Upvotes: 5

Views: 11126

Answers (4)

Subham
Subham

Reputation: 411

x = [-5,-3,-1,1,3,5]

# First min is actual min, second is based on absolute 
sort = lambda x: [min(x),min([abs(i) for i in x] )]

print(sort(x)) 
[-5, 1]

[Program finished]

Upvotes: 0

NPE
NPE

Reputation: 500167

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

Upvotes: 8

shantanoo
shantanoo

Reputation: 3705

Using functools.reduce

>>> from functools import reduce
>>> a = [-5,-3,-1,2,3,5]
>>> reduce(lambda x,y: x if 0 <= x <=y else y if y>=0 else 0, a)
2
>>> min(a)
-5
>>>

Note: This will return 0 if there are no numbers >= 0 in the list.

Upvotes: -1

Sibi
Sibi

Reputation: 48644

For getting minimum negative:

min(a)

For getting minimum positive:

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

Upvotes: 10

Related Questions