It is effective to determine if a number from a series of subsequent numbers is in an ordered list. (in Python)

We have an ordered list of numbers. Now we want to check if the list of members is within the range.

Something like range(5, 10) in mylist If in my list is 5,6,7,8 or 9, it should return an element that is first in the list, otherwise Null or False.

For example, if mylist is something like [1,2,3,7,8,10,15], the function will return 7. If there is a list [1,2,3,4,12,13], the function will return None / False.

Now think of large lists and large ranges, and the operation becomes ineffective. How can I implement this so that it has better performance?

+4
source share
1 answer

, ( bisect.bisect_left()).

, (return None).

, start_index ( start_index - , start).

:

import bisect
def intersect_range(lst, start, stop):
     start_i = bisect.bisect_left(lst, start)
     stop_i = bisect.bisect_left(lst, stop)
     if start_i == stop_i:
         return None
     else:
         return lst[start_i]

intersect_range([1,2,3,7,8,10,15], 5, 10)
=> 7
intersect_range([1,2,3,7,8,10,15], 5, 6)
=> None
intersect_range([1,2,3,7,8,10,15], 15,30)
=> 15
intersect_range([1,2,3,7,8,10,15], 0,1) # "stop" is excluded from range
=> None

, - O (logN), N - .


EDIT:

, , , lst[start_index] (start <= lst[start_i] < stop). logN . :

def intersect_range(lst, start, stop):
    start_i = bisect.bisect_left(lst, start)
    if start <= lst[start_i] < stop:
        return lst[start_i]
    else:
        return None
+5

All Articles