【问题标题】:Why can't I set default parameters to a recursive binary search function?为什么我不能为递归二分搜索函数设置默认参数?
【发布时间】:2019-08-09 00:07:45
【问题描述】:

我正在阅读一本关于 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))

【问题讨论】:

  • 将 low 和 high 作为全局变量然后 :)
  • 通常我通过为客户端代码设置一个前端函数,然后是一个递归内部细节函数来解决这个问题。但是你可以默认“high=None”,在代码集中“if high is None: high = len(data)”
  • low 和 high 总是不相同的值。您在递归到函数时正在更改它们,例如return binary_search(data, target, low, mid-1) 和 return binary_search(data, target, mid+1, high).
  • 哦,我以为你想要默认值,所以初始调用更简单。我应该更仔细地阅读。
  • @TomDalton 抱歉,我应该更好地表达自己,主调用在 99% 的情况下将具有相同的最后两个参数,而递归调用实际上是不同的。

标签: python algorithm data-structures binary-search


【解决方案1】:

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

由于您是从一本试图教您一些有关数据结构的书中得到的,我想他们省略了这一点,以便更容易理解。

正如您所写,您不知道默认的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

【讨论】:

  • 就像一个魅力,这对于其他递归问题也很有用。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
  • 2013-05-31
  • 2012-10-28
  • 2015-04-30
  • 1970-01-01
  • 2015-04-06
相关资源
最近更新 更多