5

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
0

4 Answers 4

10

For getting minimum negative:

min(a)

For getting minimum positive:

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

Sign up to request clarification or add additional context in comments.

2 Comments

There is no need to import reduce.
min(a) will give a positive number in case the list contains only positive values
8
>>> 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.

Comments

0
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]

Comments

-1

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.

1 Comment

using reduce for functools looks like an overkill =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.