为什么我不能为递归二进制搜索函数设置默认参数?
Why can't I set default parameters to a recursive binary search function?
我正在 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 阅读一本关于数据结构和算法的书,它包含一个二进制搜索函数的示例,我意识到了一些事情......该函数有 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