Python 递归函数返回无?
为了实现我自己的二进制搜索,我编写了以下函数Python 递归函数返回无?,python,recursion,Python,Recursion,为了实现我自己的二进制搜索,我编写了以下函数 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], t
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)
但它没有返回任何结果。此外,当我直接调用对分(['d'],'d')时,我得到了正确的值0。这怎么可能呢?您忽略了递归调用的返回值。您还需要显式返回这些值:
elif input[mid] > target:
return bisect(input[:mid], target)
elif input[mid] <= target:
return bisect(input[mid:], target)
elif输入[mid]>目标:
返回对分(输入[:中间],目标)
elif输入[mid]的可能重复项
elif input[mid] > target:
return bisect(input[:mid], target)
elif input[mid] <= target:
return bisect(input[mid:], target)