fredrik fredrik - 2 months ago 9
Python Question

Find next lower value in list of (float) numbers?

How should I write the

find_nearest_lower
function?

>>> values = [10.1, 10.11, 10.20]
>>> my_value = 10.12
>>> nearest_lower = find_nearest_lower(values, my_value)
>>> nearest_lower
10.11


This needs to work in Python 2.6 without access to numpy.

Answer
>>> def find_nearest_lower(seq, x):
...     return max(item for item in seq if item < x)
...
>>> values = [10.1, 10.11, 10.20]
>>> my_value = 10.12
>>> nearest_lower = find_nearest_lower(values, my_value)
>>> nearest_lower
10.11

This approach will raise an exception if there aren't any values in seq that are smaller than x. If this is undesirable behavior, you could instead return a sentinel value, such as None:

def find_nearest_lower(seq, x):
    candidates = [item for item in seq if item < x]
    if not candidates: return None
    return max(candidates)

Or

def find_nearest_lower(seq, x):
    try:
        return max(item for item in seq if item < x)
    except ValueError:
        return None

... If you're more of an "ask forgiveness" person than a "look before you leap" person.

Comments