I have a sorted list and i need to position an element within that list such that the previous element is <= and the next element in the list is > (the list is a list of floating point numbers)
I shall need to return the position of the element that is <= i.e. the previous element
how can i implement this in logarithmic time. i thought of using a method similar to binary seacrh but couldn't get it to work
Any help would be appreciated
P.S. an example is:if the list is
testlist=[0.0, 0.25, 0.5, 0.75, 1.0]
and i run the function for 0.27 the function will return 1 (the location of 0.25) and if i run it for 0.5 it'll return 2
There is a dedicated 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With