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. .
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
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
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)
If you can use numpy:
a = np.array([-1.2, 1, 0.5, 4, 5, 3])
min(a[(a<2) & (a > 0.2)])
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. .
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
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
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)
If you can use numpy:
a = np.array([-1.2, 1, 0.5, 4, 5, 3])
min(a[(a<2) & (a > 0.2)])