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

时间:2015-02-27 17:21:28

标签: python python-3.x recursion return

(...不要询问数组的价值,他们是与一些朋友开玩笑的拉美食品品牌。)

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"))和{{1 }}:

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

显然应该返回None None 3,但它什么都不返回。我做错了什么?

1 个答案:

答案 0 :(得分:3)

你没有回来:

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