【问题标题】:Recursive function returning none?递归函数不返回?
【发布时间】:2015-10-22 18:23:39
【问题描述】:

为了实现我自己的二分查找,我写了下面的函数

def bisect(input, target):
    mid = len(input)/ 2
    if len(input) == 1:
        if input[0] == target:
            return 1
        else:
            return None
    elif input[mid] > target:
        bisect(input[:mid], target)
    elif input[mid] <= target:
        bisect(input[mid:], target)

我知道我的实现已关闭,但我更想了解这里的递归堆栈。

当我调用bisect(['d','e'], 'd') 时,我的函数应该返回

bisect(['d'], 'd')

但它返回 None。此外,当我直接调用bisect(['d'], 'd')时,我得到了正确的值0。这怎么可能?

【问题讨论】:

标签: python recursion


【解决方案1】:

您忽略了递归调用的返回值。您也需要明确地返回它们:

elif input[mid] > target:
    return bisect(input[:mid], target)
elif input[mid] <= target:
    return bisect(input[mid:], target)

递归调用就像任何其他函数调用一样;他们将结果返回给调用者。如果忽略返回值,然后调用函数结束,则最终会得到该调用函数,然后返回 None

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 2012-09-21
    • 2016-06-30
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多