【发布时间】: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