【问题标题】:Implement binary search subroutine but no outcome执行二分查找子程序但没有结果
【发布时间】:2021-04-04 18:03:03
【问题描述】:

算法细节:

给定一个包含 n 个元素的数组 A,其排序值为 A[0] ≤ A[1] ≤ ... ≤ A[n−1],目标值为 x,以下子例程使用二分查找来查找 x 在 A 中的索引。

这是我写的代码:

def Binarysearch(A, x): 
    L = 0 
    R = len(A)-1 
    M = (L + R)//2 
    while L<=R: 
        if A[M] < x: 
            L = M+1 
        elif A[M] > x: 
            R = M-1 
        else: 
            return M 
    
    return None 

问题: 通过编写以下几行,我没有得到任何结果:

list = [2,3,4,5,12,15,76]
Binarysearch(list, 3)

我想了解问题所在。 我注意到,如果我在 else 条件之后替换: return M with print(M) 我得到一个无限序列 1。

【问题讨论】:

  • 也许你的意思是使用函数值的返回值并打印出来?
  • 您是否熟悉交互式在线工具 - 例如。 http://www.pythontutor.com/ - 如果你运行你的代码,更容易看出哪里出错了。
  • 旁白:不要命名你的变量list;当您尝试使用 list 内置时,它会导致令人困惑的问题。

标签: python function search indexing


【解决方案1】:

问题在于这一行:

M = (L + R)//2

需要在循环内。否则,M 永远不会更新,并且您将进入无限循环。

【讨论】:

    【解决方案2】:

    正如@BrianMcCutchon 之前的帖子所指出的,代码和工作解决方案存在缺陷。你概率。现在已经很好地掌握了这个问题。

    我刚刚在此处提供了具有更多描述性变量名称的 same 解决方案供您参考。

    def binary_iterative(A, target):
        ''' 
        Return the index of the target, or None if not found.
    
        The array A is in sorted order, and assumed each num. is unique.
        ''' 
    
        left, right = 0, len(A) - 1
    
        while left <= right:
    
            middle_idx = (left + right) // 2
            middle_num = A[middle_idx]
    
            if middle_num == target:
                return middle_idx
            
            elif middle_num < target:
                left = middle_idx + 1
                
            elif middle_num > target:
                right = middle_idx - 1
                
        return None
    
    
    
    if __name__ == '__main__':
        nums = [1, 3, 4, 5, 6, 9, 10, 12, 17, 20, 22]
        target = 5
        print(binary_iterative(nums, target))
       
    
    

    【讨论】:

      猜你喜欢
      • 2012-10-16
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 2014-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多