Skip to content Skip to sidebar Skip to footer

Python Binary Search-like Function To Find First Number In Sorted List Greater Than A Specific Value

I'm trying to write a function in Python that finds the first number in a sorted list greater than a specific value that I pass in as an argument. I've found examples online that

Solution 1:

Have you tried the bisect module?

deffind_ge(a, key):
    '''Find smallest item greater-than or equal to key.
    Raise ValueError if no such item exists.
    If multiple keys are equal, return the leftmost.

    '''
    i = bisect_left(a, key)
    if i == len(a):
        raise ValueError('No item found with key at or above: %r' % (key,))
    return a[i]

find_ge(somenumbers, 262139)

Your code is wrong that (1) low > high is a valid termination case. (2) you should not stop at low == high, e.g. it will return an incorrect index when num == 3 for your somenumbers.

Solution 2:

If you need the implementation without bisect function, you can try the following code:

deffindFirstLargerOrEqual(num, sortedList):
    '''Finds the smallest index in the sortedList
    of the element which is greater-than or equal to num'''

    slen = len(sortedList)
    start = 0while slen > 0:
        m = start + slen//2if sortedList[m] < num:
            slen = slen - (m+1 - start)
            start = m+1continueif start < m and sortedList[m-1] >= num:
            slen = m - start
            continuereturn somenumbers[m]

    raise ValueError('Not found')

somenumbers=[n*2for n inrange(131072)]
print(findFirstLargerOrEqual(262139, somenumbers)) #output: 262140

Post a Comment for "Python Binary Search-like Function To Find First Number In Sorted List Greater Than A Specific Value"