【问题标题】:recursive binary search, biesction by slicing递归二分查找,通过切片进行分类
【发布时间】:2021-10-25 23:47:49
【问题描述】:

我正在尝试使用递归在整数列表上实现二进制搜索,并通过每次对列表进行切片来“消除”一半的项目。我写了一些,如果达到目标值,我有点卡在我应该返回“True”的部分。我会反复检查“左”是否大于“右”,但我想让函数的参数尽可能简单。

def binary_search(iterable, target):

    left_index = 0
    right_index = len(iterable)
    mid = (left_index + right_index) // 2

    if iterable[mid] == target:
        return True
    elif iterable[mid] < target:
        iterable = iterable[mid:right_index]
        print(iterable)
        binary_search(iterable,target)
    elif iterable[mid] > target:
        iterable = iterable[left_index:mid]
        print(iterable)
        binary_search(iterable,target)

【问题讨论】:

  • “我会反复检查 'left' 是否大于 'right',但我想让函数的参数尽可能简单。” - 为什么会 '左”是否大于“右”?为了使二分搜索起作用,必须对输入进行排序。
  • 因为这是返回 False 的条件,因为这意味着该项目不在列表中,也许我解释得不好
  • 如果您想查看您的回报,只需在两个 elif 中的所有函数调用之前添加return,如果您的输入已排序,您也不需要 2 个 elif。但这只是为了你不会得到None,如果有人输入不在列表中的数字,你仍然会遇到很多问题,你会得到一个无限循环。

标签: python recursion binary-search


【解决方案1】:

如果找不到该值,则以下返回False;否则返回索引。二分查找递归执行。

您的代码的关键补充是returning 您的函数调用。我添加了一些return a+b if a != False else a 逻辑,以处理返回的False 如果值不在可迭代对象中。

def binary_search(iterable, target):
    # if the list is down to one element, and it isn't the target, return False
    if len(iterable) == 1 and iterable[0] != target: return False
        
    left_index = 0
    right_index = len(iterable)
    mid = (left_index + right_index) // 2

    if iterable[mid] == target:
        return mid
    elif iterable[mid] < target:
        iterable = iterable[mid:right_index]
        v = binary_search(iterable,target)
        # if v is not False, add it to the left side of the window and return
        # else return False
        return v + mid if v != False else v
    elif iterable[mid] > target:
        iterable = iterable[left_index:mid]
        v = binary_search(iterable,target)
        return v + left_index if v != False else v

【讨论】:

  • 如果数字在列表中,我想返回 True,如果不只是针对初学者,我想返回 false,现在我的搜索在某些阶段停止,没有返回任何内容。例如,如果我这样调用函数: print(binary_search([1,2,3,4,5,6,7],7)) 我会打印出来: [4, 5, 6, 7] [ 6, 7] 无
猜你喜欢
  • 2016-01-19
  • 2015-12-16
  • 2012-12-19
  • 1970-01-01
  • 2020-11-13
  • 2021-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多