For my project I need to repeatedly find the indices of timestamps in lists and if the exact timestamp is not in the list I need to find the index of the timestamp right before the one I'm looking for. I tried looping through the list, but that's very slow:
def find_item_index(arr, x):
'''
returns index of x in ordered list.
If x is between two items in the list, the index of the lower one is returned.
'''
for index in range(len(arr)):
if arr[index] <= x < arr[index+1]:
return index
raise ValueError(f'{x} not in array.')
I also tried to do it recursivly, but that was even slower:
def find_item_index_recursive(arr, x, index = 0):
'''
returns index of x in ordered list.
If x is between two items in the list, the index of the lower one is returned.
'''
length = len(arr)
if length == 1:
return index
if arr[length // 2] < x:
return find_item_index_recursive(arr[length // 2:], x, index + length // 2)
else:
return find_item_index_recursive(arr[:length // 2], x, index)
raise ValueError(f'{x} not in array.')
Is there a faster way to do this?