[英]modifying iterative function to be recursive
我有一个交互函数,它接受一系列整数并返回目标项目的索引位置或返回目标应插入的位置。(如果项目不在列表中)
该函数效果很好,但我试图找出在不借助任何辅助函数的情况下将该函数从迭代实现更改为递归实现的最精简方法。
def binary_search(a_list, first, last, target):
"""a sequence of integers, index of first item, index of last item, target to search for """
while first <= last:
middle = (first + last) // 2
if a_list[middle] == target:
return middle
if target < a_list[middle]:
last = middle - 1
else:
first = middle + 1
return first
print(binary_search([2, 5, 8, 11, 17], 0, 4, 5))
这个怎么样:
def binary_search_recursive(a_list, first, last, target):
middle = (first + last) // 2
number = a_list[middle]
if first > last:
return first
if number == target:
return middle
if target < number:
return binary_search_recursive(a_list, first, middle-1, target)
else:
return binary_search_recursive(a_list, middle+1, last, target)
编辑:代码中有一个小错误——现在更正了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.