【问题标题】:How can I make this offset binary search return None if the item is not found?如果找不到该项目,如何使此偏移二进制搜索返回 None?
【发布时间】:2018-02-26 22:44:55
【问题描述】:

我必须使用偏移量进行二进制搜索,所以没有左或右变量。如果找不到该项目,我需要让它返回 None ,但无论出于何种原因,我都对如何做到这一点感到困惑。我知道你能做到

if right >= left:
    #search function here
else: return None

但我没有这些变量,它不适用于 array[mid:] >= array[:mid]

这里是函数

def binary_search(array, item, offset=0):
    mid = int(len(array)/2) #make mid an int so it truncates

    if item == array[mid]: #if the item is at mid, we're done
        return mid + offset
    elif item > array[mid]: #if the item is bigger than the item at mid, go to right side of array
        return binary_search(array[mid:], item, offset+mid) #add the mid value to offset since we're going right
    else: #otherwise, the value is smaller and we go to the left side of the array
        return binary_search(array[:mid], item, offset) #leave offset the same

我尝试了很多不同的东西,但我似乎无法弄清楚。谢谢!

【问题讨论】:

    标签: python offset binary-search


    【解决方案1】:

    观察这些事实并使用它们来调整您的算法:

    • 正如所写,您的函数将始终返回一个整数,因为mid + offset 是一个整数。如果您想返回 None,则需要在某处空出 returnif/elif/else 链永远不会失败)。
    • 您需要在某处进行递归的停止条件。你目前确实有一个(在评论“如果项目在中间,我们完成”之后)。但是,您将需要另一个不同的 return 来处理该值不存在的情况
    • 如果您收到一个空数组作为输入,mid 将被计算为索引 0。这看起来对吗...?
    • 切片array[mid:] 包括索引mid 处的项目。在array[:mid] 处切片包含索引mid 处的项目。在 if/elif/else 的三个分支中寻找任何逻辑重叠。

    【讨论】:

    • 我得到的最接近的事情是添加 if mid ==0: 在 mid 计算之后返回 None。这有效,除非我正在搜索最左边的项目,该项目的中间值为零,返回无。至于你的第四点,如果我在数组 [mid+1:] 处切片,偏移值会被丢弃,所以我认为我必须保留它。
    • 在计算中间之后添加 找到了解决方案。今天我一直盯着这个屏幕太久了哈哈谢谢你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 2020-04-02
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    相关资源
    最近更新 更多