Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python recipe: list item nearest equal to value [closed]

Tags:

python

Considering a list like [0,3,7,10,12,15,19,21], I want to get the nearest minimum digit closest to any value, so if I pass 4, I would get 3, and if I pass 18, I would get 15, etc.

like image 771
Wells Avatar asked Aug 12 '26 22:08

Wells


1 Answers

You can use bisect which isn't too difficult. It's used for binary searching like this. This does assume a sorted list.

from bisect import bisect_right

def find_le(a, x):
    'Find rightmost value less than or equal to x'
    i = bisect_right(a, x)
    if i:
        return a[i-1]
    raise ValueError

mylist = [0,3,7,10,12,15,19,21]
print find_le(mylist,4)
print find_le(mylist,-1)
print find_le(mylist,29)
print find_le(mylist,12)

Running interactive:

>>> print find_le(mylist,4)
3
>>> print find_le(mylist,-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in find_le
ValueError
>>> print find_le(mylist,29)
21
>>> print find_le(mylist,12)
12
like image 184
woot Avatar answered Aug 15 '26 13:08

woot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!