【问题标题】:Index going out of range in bisect_left in Python 3Python 3 中 bisect_left 中的索引超出范围
【发布时间】:2020-01-28 10:51:18
【问题描述】:

我正在编写这段代码,其中我使用了 bisect 模块中的 bisect_left 函数,该模块是 Python 的第一方模块。我只使用两个参数,即 sorted_list 和 target(我必须为其找到合适的索引值)。

问题是:如果我的目标大于最小值和最大值的总和,则函数返回 index = len(sorted_li),因此我收到索引错误。我可以使用 try 和 except,但不仅如此,我很想知道它为什么会这样。

以下是我的代码:

from bisect import bisect_left

li = [10,15,3,6,10]
k  = 19

def binary_search(sorted_list,target):

    index = bisect_left(sorted_list,target)

    print(index)

    if sorted_list[index] == target:
        return index

    else:
        return False

def function(sorted_li,k):

    """
    Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
    For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
    """

    print(sorted_li)

    for i in range(len(sorted_li)):

        print('Next iteration')

        print(sorted_li[i])

        target = k - sorted_li[i]

        j = binary_search(sorted_li,target)

        if j:
            if j != i:
                print(sorted_li[i])
                print(sorted_li[j])
                return True
            else:
                if j + 1 < len(sorted_li):
                    if sorted_li[j+1] == target:
                        print(sorted_li[i])
                        print(sorted_li[j+1])
                        return True
                if j - 1 > 0:
                    if sorted_li[j-1] == target:
                        print(sorted_li[i])
                        print(sorted_li[j-1])
                        return True
    return False


if __name__ == "__main__":

    li.sort()
    a = function(li,k)
    print(a)

它的输出如下:

但是当我将k改为18时,代码运行正常,输出如下:

我已经尝试过使用不同的数字集。输出保持不变。

【问题讨论】:

    标签: python-3.x binary-search


    【解决方案1】:

    您正在使用bisect_left,它的下一个目的是:它寻找 x 的插入点(在您的情况下是目标)以保持排序顺序。

    因此,对于您的情况,当您第一次为 16 (19 - 3) 调用 binary_search 时,它会使用二进制算法将您的数字与 li 列表中的项目进行比较,然后返回插入 5 的位置,因为在您的列表中 [3, 6, 10, 10, 15] 插入点应该在 15 之后,这是正确的。

    如果你打开documentation,你可以在searching sorted list找到下一个方法

    这正是您需要的,它在列表中搜索确切的项目并返回它的位置,如果它存在,它会引发ValueError,因为找不到项目。

    def index(a, x):
        'Locate the leftmost value exactly equal to x'
        i = bisect_left(a, x)
        if i != len(a) and a[i] == x:
            return i
        raise ValueError
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 2018-05-06
      • 2016-02-14
      相关资源
      最近更新 更多