【问题标题】:Python binary search can not solvePython二分查找解决不了
【发布时间】:2021-03-22 05:32:52
【问题描述】:

我在学习二分搜索时遇到了麻烦。这是我的代码:

a = [1, 2, 4, 6, 7, 8, 11, 13, 23, 26, 28, 32, 36, 402, 2403, 3340, 4400]


def binary_search(list, whattosearch):
    start_index = 1
    end_index = len(list) - 1
    while True:
        mid_index = (end_index - start_index) // 2
        if mid_index < start_index or mid_index > end_index or mid_index < 0:
            return False

        mid_element = list[mid_index]
        if mid_element == whattosearch:
            return True
        if mid_element < whattosearch:
            start_index = mid_index
        else:
            end_index = mid_index

if __name__ == '__main__':
print(binary_search(a, 8))

我得到 'False' 作为输出。有人可以帮帮我吗?

【问题讨论】:

  • 当你运行代码时,你会到达一个点,你的结束索引是 7,你的开始索引是 3,你将中点设置为 (end - start) // 2,所以 (7 - 3 ) // 2 thats 4 // 2 which is 2. 所以你现在的中点小于起点。你的代码说如果 mid 小于 start return false
  • 您应该将中点设置为起点+终点与起点之间的差除以2。类似mid_index = start_index + ((end_index - start_index) // 2)

标签: python list function search binary


【解决方案1】:

您不应该使用list 作为变量名,因为它是为list 类型保留的。 start_index 应该初始化为 0。二分查找也不需要 while True。一般来说:

# You can replace 
    while True:
# with:
    while start <= end:

# Remove
        if mid_index < start_index or mid_index > end_index or mid_index < 0:
            return False
# And add return False after the while loop.

# And use
            start = mid + 1  instead of start = mid
            end = mid - 1 instead of end = mid
# To avoid any indexing issues.

【讨论】:

    【解决方案2】:

    我已经简化了你的二分搜索代码

    a = [1, 2, 4, 6, 7, 8, 11, 13, 23, 26, 28, 32, 36, 402, 2403, 3340, 4400]
    
    
    def binary_search(list, whattosearch):
        start_index = 0. # should not be 1
        end_index = len(list)
        while start_index<end_index:
            mid_index = (end_index + start_index) // 2
            mid_element = list[mid_index]
            if mid_element == whattosearch:
                return True
            if mid_element < whattosearch:
                start_index = mid_index + 1 # needs to move ahead of mid point
            else:
                end_index = mid_index
        return False
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      相关资源
      最近更新 更多