Position element in an ordered list in Python logarithmic time

I have a sorted list and I need to put an item in this list so that the previous item is <= and the next item in the list -> (list is a list of floating point numbers)

I will need to return the position of an element which is <= ie of the previous element

how can i implement this in logarithmic time. i thought about using a method similar to seacrh binary but couldn't get it to work

Any help would be appreciated

PS example: if the list

testlist=[0.0, 0.25, 0.5, 0.75, 1.0]

      

and i run the function for 0.27 the function will return 1 (place 0.25) and if i run it at 0.5 it will return 2

+3


source to share


1 answer


There is a special module for binary search: bisect



import bisect

testlist=[0.0, 0.25, 0.5, 0.75, 1.0]
print bisect.bisect(testlist, .27) - 1
## 1

      

+3


source







All Articles