gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:26:36 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com