python: minimum value within specified bounds for an array

Question:

Say I have an array a = [-1.2, 1, 0.5, 4, 5, 3]

Is there a way to find a min element which is within a=0.2 to b=2

In this particular example the answer will be 0.5.

I want to perform this computation in python. .

Asked By: user1612986

||

Answers:

a = [-1.2, 1, 0.5, 4, 5, 3]
r1=0.2 
r2=2
l=[]
for i in a:
    if i>r1 and i<r2:
        l.append(i)
print(min(l))

I have considered strictly inside two given value, use >= and <= if both are to be included .Hope this helps

Answered By: snehil

If you extend the list with your bounds (Min=0.2 and Max=2), you can get the elements between by indexing after sorting the extended list:

a =  [-1.2, 1, 0.5, 4, 5, 3]
# Define bounds
Min = 0.2
Max = 2
# Extend and sort list with integrated bounds
a = sorted(a + [Min, Max])
# Slicing and get all the elements between bounds
print(min(a[a.index(Min)+1:a.index(Max)]))
# 0.5
Answered By: Laurent B.

You can use filter(predicate, list) or a generator expression to eliminate the out-of-bounds values, then use min(iterable) on the remaining elements:

a = [-1.2, 1, 0.5, 4, 5, 3]
assert 0.5 == min(filter(lambda x: 0.2 <= x <= 2, a))
# or
assert 0.5 == min(x for x in a if 0.2 <= x <= 2)
Answered By: das-g

If you can use numpy:

a = np.array([-1.2, 1, 0.5, 4, 5, 3])
min(a[(a<2) & (a > 0.2)])
Answered By: Osman Mamun
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.