【问题标题】:Binary search: weird middle point calculation二分搜索:奇怪的中间点计算
【发布时间】:2018-02-01 22:06:56
【问题描述】:

关于列表中点的计算:为什么会有

i = (first +last) //2 

并且last 被初始化为len(a_list) - 1?根据我的快速测试,这个算法没有 -1 可以正常工作。

def binary_search(a_list, item):
    """Performs iterative binary search to find the position of an integer in a given, sorted, list.
    a_list -- sorted list of integers
    item -- integer you are searching for the position of
    """

    first = 0
    last = len(a_list) - 1

    while first <= last:
        i = (first + last) / 2

        if a_list[i] == item:
            return '{item} found at position {i}'.format(item=item, i=i)
        elif a_list[i] > item:
            last = i - 1
        elif a_list[i] < item:
            first = i + 1
        else:
            return '{item} not found in the list'.format(item=item)

【问题讨论】:

    标签: python algorithm search


    【解决方案1】:

    最后一个合法索引len(a_list) - 1。算法正常工作,因为first 永远不会超过这个,因此截断的平均值永远不会超出范围。但是,如果没有 -1,中点计算将在大约一半的时间内比最优值大一,导致速度略有损失。

    【讨论】:

      【解决方案2】:

      考虑您要搜索的项目大于列表中所有元素的情况。在这种情况下,语句first = i + 1 会重复执行。最后你到达循环的最后一次迭代,first == last。在这种情况下i 也等于last,但如果last=len()i 不在列表的末尾!第一个 if 语句将因索引超出范围而失败。

      自己看看:https://ideone.com/yvdTzo

      您的代码中还有另一个错误,但我会让您自己找到它。

      【讨论】:

      • 你的意思是 / 而不是 // ?
      • @filemonczyk 不,因为/ 在 Python 2 中会非常好。自己尝试一些测试用例,看看会发生什么。
      • 我刚刚注意到,如果 while 谓词不匹配,它往往会跳过最后一个返回,并导致返回 'None',我认为它在 python 中为空。例如 binary_search([], 0)。没有设法得到任何运行时错误
      • @filemonczyk 是的,就是这样!问题,最后的else之后的代码什么时候执行?
      • 现在当我阅读代码时,它看起来永远不会被执行,因为一个数字可以或多或少等于特定值,
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 2012-04-12
      相关资源
      最近更新 更多