修改迭代函数是递归的

时间:2018-02-05 18:22:08

标签: python algorithm

我有一个迭代函数,它接受一个整数序列并返回目标项的索引位置或返回目标应该插入的位置。(如果项目不在列表中

该功能运行良好,但我试图弄清楚在没有任何辅助功能的帮助下,将这个功能从迭代改为递归实现的最简单方法是什么。

  changeTitle(newTitle){
    this.setState(({directions,currentDirectionsIndex}) => ({
         directions: directions.map((direction,index)=> 
         index===currentDirectionsIndex? ({...direction,title:{rendered:newTitle}}):direction
    })

1 个答案:

答案 0 :(得分:1)

这个怎么样:

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)

编辑:代码中有一个小错误 - 现已更正。

相关问题