Home > Enterprise >  given a sorted list, find the index of number
given a sorted list, find the index of number

Time:09-23

Given a sorted list and a number n, find the index in the list that precedes n in the most efficient (fastest) way.

sorted list example:

x_list = [1, 3.5, 5, 9.2, 20, 50.75]

number n, say n = 7.5

Example answer: the index of the value in the list that precedes n is 2.

This is what i have tried so far:

x_list = [1, 3.5, 5, 9.2, 20, 50.75]

n = 7.5
for i, v in enumerate(x_list):
    if v < n: xlow = i
    else: break
print(xlow)

Can i do a quicker find than the above method ?

Note: This list is sorted whereas other questions of the same nature are unsorted.

CodePudding user response:

You can use bisect to perform a binary search:

import bisect

n = 7.5

index = bisect.bisect_left(x_list, n)-1

output: 2

NB. In case the target is before the first index, this will return -1, which you can avoid using max(0, bisect.bisect_left(x_list, n)-1) if needed.

  • Related