【发布时间】:2019-03-19 23:22:53
【问题描述】:
我尝试使用二等分算法搜索查找的索引
def bi_search(nums: List[int], find: int) -> int:
"""
Return the index of the find
"""
if len(nums) == 0:
return -1
else:
mid = len(nums) // 2 #testEntry
if find == nums[mid]:
return mid
if find < nums[mid]:
sub_nums = nums[:mid]
return bi_search(sub_nums, find)
if find > nums[mid]:
sub_nums = nums[mid:]
return bi_search(sub_nums, find) #recursive case.
但它没有按预期工作
In [26]: bi_search(list(range(1000)), 777)
Out[26]: 4
它返回基本情况的中间。
我注意到可以使用 bisect — Array bisection algorithm — Python 3.7.3rc1 documentation 中的迭代方法检索正确的索引
是否有可能在递归解决方案中获得正确的索引?
【问题讨论】:
-
正确的索引?你的方法更难。这是因为在最后一次迭代中,nums 将类似于 [773,774,775,776,777,778,779,780,781,782]。一个可行的递归解决方案是使用像 bi_search(nums, lower_bound, upper_bound) 这样的函数,您可以确定目标元素位于 lower_bound 和 upper_bound 的索引之间。你只需传递 nums 而不切片它。
标签: python python-3.x recursion bisection