Python binary search-like function to find first number in sorted list greater than a specific value

后端 未结 2 1788
南笙
南笙 2020-12-17 06:08

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 onl

相关标签:
2条回答
  • 2020-12-17 06:36

    Have you tried the bisect module?

    def find_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.

    0 讨论(0)
  • 2020-12-17 06:39

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

    def findFirstLargerOrEqual(num, sortedList):
        '''Finds the smallest index in the sortedList
        of the element which is greater-than or equal to num'''
    
        slen = len(sortedList)
        start = 0
    
        while slen > 0:
            m = start + slen//2
    
            if sortedList[m] < num:
                slen = slen - (m+1 - start)
                start = m+1
                continue
    
            if start < m and sortedList[m-1] >= num:
                slen = m - start
                continue
    
            return somenumbers[m]
    
        raise ValueError('Not found')
    
    somenumbers=[n*2 for n in range(131072)]
    print(findFirstLargerOrEqual(262139, somenumbers)) #output: 262140
    
    0 讨论(0)
提交回复
热议问题