python - 为什么我的递归二分搜索函数没有返回任何内容?

标签 python python-3.x recursion return

(...不要问数组值,它们是拉丁美洲食品品牌,已成为一些 friend 的内部笑话)。

def binSearch(arr, i, lower=0, upper=None):
    if upper is None:
        upper = len(arr)+1
    idx = (lower+upper)//2
    if arr[idx] == i:
        print(idx, arr[idx],'\n')
        #return idx
    elif arr[idx] != i and upper-lower<2:
        print("Not found \n")
        #return False
    elif arr[idx] < i:
        print(idx, arr[idx])
        binSearch(arr, i, idx, upper)
    elif arr[idx] > i:
        print(idx, arr[idx])
        binSearch(arr, i, lower, idx)

myArray = ["Chabona", "F-Nandito VII", "La Bichy", "Manaos", "Martín y Enzo", "Pitusas", "Trompis", "Ugi's", "VAMOS MANAOS", "Villamanaos"]

binSearch(myArray, "Manaos")
binSearch(myArray, "Coca-Cola")

这个程序完全按照我的预期执行 - 它输出如下:

5 Pitusas
2 La Bichy
3 Manaos 

5 Pitusas
2 La Bichy
1 F-Nandito VII
Not found

但是,这就是当我注释掉所有打印语句以使其返回 idxNone ,然后用 替换调用时得到的结果print(binSearch(myArray, "Manaos")) print(binSearch(myArray, "Coca-Cola")) :

None
None

它显然应该返回 3False 但它什么也没返回。我做错了什么?

最佳答案

您不会返回:

return binSearch(arr, i, lower, idx)

您还需要返回您的条件:

def binSearch(arr, i, lower=0, upper=None):
    if upper is None:
        upper = len(arr)+1
    idx = (lower+upper)//2
    if arr[idx] == i:
        print(idx, arr[idx],'\n')
        return idx # return 3/idx
    elif arr[idx] != i and upper-lower<2:
        print("Not found \n")
        return False  # return False
    elif arr[idx] < i:
        print(idx, arr[idx])
        return binSearch(arr, i, idx, upper)
    elif arr[idx] > i:
        print(idx, arr[idx])
        return binSearch(arr, i, lower, idx)

print(binSearch(myArray, "Manaos"))
print(binSearch(myArray, "Coca-Cola"))

5 Pitusas
2 La Bichy
3 Manaos 

3
5 Pitusas
2 La Bichy
1 F-Nandito VII
Not found 

False

关于python - 为什么我的递归二分搜索函数没有返回任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770770/

相关文章:

python - 在ansible中提取最后两个IP

python - celery 任务分组/聚合

python - 当特定数量不在特定列中时如何删除数据框的行?

mysql - 我正在尝试解析本地磁盘上的 350 个文件并将数据作为 json 对象存储到数据库中

scala - 递归集联合 : how does it work really?

c++ - 关于C++中的递归函数(初级)

c++ - 在 C++ 中使用递归函数反转字符串

python - 如何在 mac osx 上的子进程中打开文件

python - 如何在没有互联网连接的情况下从源代码安装 python?

python - 使用 Tensorflow 作为 Anaconda 的环境