let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n).
My O(n) approach:
index=0
for i,value in enumerate(mylist):
if value>compareValue:
index=i-1
Is there a datatype for solving that problem in O(log n)?
sorted() , with no additional arguments or parameters, is ordering the values in numbers in an ascending order, meaning smallest to largest. The original numbers variable is unchanged because sorted() provides sorted output and does not change the original value in place.
We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value.
The sort() method is a list method that modifies the list in-place and returns None. In other words, the sort() method modifies or changes the list it is called on, and does not create a new list.
How about bisect?
>>> import bisect
>>> float_list = [1.0, 1.3, 2.3, 4.5]
>>> i = bisect.bisect_left(float_list, 2.5)
>>> index = i - 1
>>> index
2
You might have to handle the case of a search value less than or equal to the lowest / leftmost value in the list separately (index == -1
in this case).
Depending on which index you want to have in case of equality, you might have to use bisect_right
instead.
You can do a binary search on an array/list to get the index of the object you're looking for and get the index below it to get the lower entry (given that there actually is a lower entry!).
See: Binary search (bisection) in Python
Be careful when comparing floating point numbers for equality!
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