Search code examples
pythonarraysmaxmin

python: minimum value within specified bounds for an array


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


Solution

  • 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)