Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find next lower item in a sorted list

Tags:

python

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)?

like image 949
Sebastian Avatar asked Apr 07 '10 09:04

Sebastian


People also ask

How does sorted() work?

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.

How do you find the index of the closest value in a list Python?

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.

Does sorted change the list Python?

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.


2 Answers

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.

like image 158
stephan Avatar answered Oct 29 '22 16:10

stephan


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!

like image 26
Bart Kiers Avatar answered Oct 29 '22 14:10

Bart Kiers