python - 为什么我不能为递归二进制搜索函数设置默认参数?

标签 python algorithm data-structures binary-search

我正在阅读一本关于 Python 中的数据结构和算法的书,其中包含一个二进制搜索函数的示例,我意识到了一些事情......该函数采用 4 个参数,但最后两个始终相同,即,low=0 和 high=len(data)。为什么我不能将它们设置为默认参数?

这里的主要问题是设置 low=0 没问题,但是 high=len(data) 会引发错误,因为显然数据列表在被赋值之前被访问。那么,有没有办法让函数自己获取低值和高值,这样我就不必将它们作为参数传递给主调用(因为递归仍然需要它们)?

def binary_search(data, target, low, high):
    """If target is found in indicated portion of a list, returns True
    The search only considers the portion from data[low] to data[high] inclusive."""

    if low > high:
        return False
    else:
        mid = (low+high) //2

        if target == data[mid]:
            return True
        elif target < data[mid]:
            #recur on the portion left of the middle
            return binary_search(data, target, low, mid-1)
        else:
            #recur on the portion right of the middle
            return binary_search(data, target, mid+1, high)

arr = [k+1 for k in range(10000)]
binary_search(arr, 4590, 0, len(arr))

最佳答案

是的,在这里设置默认参数值确实有意义。

因为你是从一本试图教你一些关于数据结构的书上得到的,我猜他们省略了这一点以使其更容易理解。

如您所写,您无法知道默认的 high 应该是多少,但您不必知道。只需使用 None 代替 - 这是一个很好的默认值:

def binary_search(data, target, low=0, high=None):
    """If target is found in indicated portion of a list, returns True
    The search only considers the portion from data[low] to data[high] inclusive."""

    if high is None:
        high = len(data)

    # the rest remains the same

关于python - 为什么我不能为递归二进制搜索函数设置默认参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57416429/

相关文章:

python - PyTorch 函数签名中的\* 是什么意思?

python-3.x - 重建 2 个顶点之间的多条最短路径的路径

arrays - 获取使用O(klogk)中的稀疏表排序的范围内的k个最小元素

python - 使用 get_form() 时 Django 管理员缺少添加/编辑按钮

python - 如何查看使用 Pandas Dataframe 保存的数据

c++ - 高效的 is_in(vector<string>& S, string P) 函数

algorithm - "Rounding"一小组颜色中最接近的颜色值

python - 使用字典进行条件执行而不是 if..elif

algorithm - Big O 理解二次 n(n+1)/2 图

python - pymc3 中具有(大)时间^2 项的分层模型中的 MCMC 收敛