为什么即使值不存在,python 的 bisect_left 也会返回有效索引?

6 python binary-search bisection python-3.x

我想查找排序数组中是否存在数字。一个数组包含从 1 到 63 的斐波那契数。下面是斐波那契数生成器和它的一些输出。

stacksize = 10000  # default 128 stack
from functools import lru_cache

@lru_cache(stacksize)
def nthfibonacci(n):
    if n <= 1:
        return 1
    elif n == 2:
        return 1
    elif n > 2:
        return nthfibonacci(n - 2) + nthfibonacci(n - 1)

 output = [nthfibonacci(k) for k in range(1,63+1)]

 # truncated output: [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,987, 
           1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368,.....]
Run Code Online (Sandbox Code Playgroud)

现在我想找到数字 7 是否存在,所以我使用 python bisection 模块使用了以下代码

from bisect import bisect_left
elem_index = bisect_left(a=output, x=7, lo=0, hi=len(arr) - 1) 
# output of elem_index is  5 ????  . But it is expected to be len(output) +1, right?   
# as we know if element is not found it returns len(array) +1 
Run Code Online (Sandbox Code Playgroud)

同样,如果我只是编写一个简单的二分搜索,它会给我正确的结果,如下所示:

def binsearch(arr, key):
    # arr.sort()
    low = 0
    high = len(arr) - 1
    while low <= high:
        mid = (low + high) // 2
        if arr[mid] == key:
            return mid
        else:
            if arr[mid] < key:
                low = mid + 1
            else:
                high = mid - 1
    return -1

print(binsearch(arr, 7)) # it gives me -1 as expected
Run Code Online (Sandbox Code Playgroud)

那么发生了什么?

cs9*_*s95 1

的文档bisect_left解释了该行为:

bisect_left(...)
    bisect_left(a, x[, lo[, hi]]) -> index

    Return the index where to insert item x in list a, assuming a is sorted.
Run Code Online (Sandbox Code Playgroud)

简而言之,bisect_left(and bisect_right) 告诉您元素存在的位置,或者如果不存在则将其插入的位置。

考虑一个人为的例子。当该值存在时,让我们在排序列表中搜索该值。

l = [1, 4, 5]
bisect.bisect_left(l, 4)
# 1
Run Code Online (Sandbox Code Playgroud)

bisect_left返回 1,因为l[1]4。现在,重复该过程,但使用该列表中不存在的值。

bisect.bisect_left(l, 3)
# 1
Run Code Online (Sandbox Code Playgroud)

在本例中,如果 3 存在于该排序列表中,l[1]您将在其中找到 3 。


这对你来说意味着什么?您所要做的就是修改函数以查询返回索引处的元素bisect_left

def binary_search(items, key):
    idx = bisect_left(items, key)
    if items[idx] != key:
         return -1

    return idx
Run Code Online (Sandbox Code Playgroud)

  • 如果“key”大于“items”中的任何值,最后一个建议将引发异常 (3认同)