递归函数没有返回? [英] Recursive function returning none?
问题描述
为了实现自己的二分查找,我编写了以下函数
I wrote the following function in order to implement my own binary search
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)
我知道我的实现已经关闭,但我更想了解这里的递归堆栈.
I know my implementation is off, but I am more curious in understanding the recursive stack here.
当我调用 bisect(['d','e'], 'd')
时,我的函数应该返回
When I call bisect(['d','e'], 'd')
, my function should return the value of
bisect(['d'], 'd')
而是返回 None.此外,当我直接调用 bisect(['d'], 'd')
时,我得到了正确的 0 值.这怎么可能?
but instead it returns None. Further, when I call bisect(['d'], 'd')
directly, I get the correct value of 0. How is this possible?
推荐答案
您忽略了递归调用的返回值.你也需要明确返回那些:
You are ignoring the return values of recursive calls. You need to explicitly return those too:
elif input[mid] > target:
return bisect(input[:mid], target)
elif input[mid] <= target:
return bisect(input[mid:], target)
递归调用就像任何其他函数调用一样;他们将结果返回给调用者.如果你忽略返回值,然后调用函数结束,你最终会得到那个调用函数,然后返回 None
.
Recursive calls are just like any other function call; they return a result to the caller. If you ignore the return value and the calling function then ends, you end up with that calling function then returning None
instead.
这篇关于递归函数没有返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!