Not the answer to this question. But I landed here trying to figure out how to get the two surrounding values for a given target item in a sorted list.
If anyone else is looking, this is what I came up with based on some of the other answers here.
import random
def get_nearest(items, target):
print(f'looking for {target}')
high_index = len(items) - 1
low_index = 0
if not items[low_index] <= target <= items[high_index]:
raise ValueError(f'The target {target} is not in the range of'
f' provided items {items[low_index]}:{items[high_index]}')
if target in items:
return target, target
while high_index > low_index:
index = int((high_index + low_index) / 2)
sub = items[index]
if sub > target:
if high_index == index:
return tuple(sorted([items[high_index], items[low_index]]))
high_index = index
else:
if low_index == index:
return tuple(sorted([items[high_index], items[low_index]]))
low_index = index
return tuple(sorted([items[high_index], items[low_index]]))
if __name__ == '__main__':
my_randoms = sorted(random.sample(range(10000000), 100000))
x = 340000
print(get_nearest(my_randoms, x))
x = 0
my_randoms = [x] + my_randoms
print(get_nearest(my_randoms, x))
x = 10000000
my_randoms.append(x)
print(get_nearest(my_randoms, x))
idx = random.randint(0, 100000)
x = my_randoms[idx]
print(get_nearest(my_randoms, x))
bisect
module: "The module is calledbisect
because it uses a basic bisection algorithm to do its work. The source code may be most useful as a working example of the algorithm (the boundary conditions are already right!)." – Jugendstil