为什么我的代码会继续打印无?

时间:2017-12-17 01:00:02

标签: python

我正在练习binary_search。我想返回'禁令',但我的代码一直返回无。我不知道为什么没有返回,虽然'禁令'存在。 *'禁令'是可变的。 我的代码是

def binary_search(ls,num):
    #print ls
    fir=ls[0]
    last=ls[-1]
    ban=(fir+last)/2
    print ban,num
    if ban > num:
        binary_search(range(fir,ban+1),num)
    elif num > ban:
        binary_search(range(ban,last+1),num)
    elif num==ban:
        print ls,ban
        return ban
ls=range(1,22) 
print binary_search(ls,10)

1 个答案:

答案 0 :(得分:0)

修正版,请参阅以下评论:

def binary_search(ls, num):
    # helper function to search the indices
    # we "know" ls and num from the outer-scope, so we'll pass only the indices
    def search(first=0, last=len(ls)):
        if first < last:
            mid = (first + last) // 2
            ban = ls[mid]
            if ban > num:
                return search(first, mid-1)
            elif num > ban:
                return search(mid+1, last)
            elif num == ban:
                return mid  # return the index - not the number itself!
        else:
            return "not found!"
    return search()


ls = list(range(1, 22))  # you should wrap range with list!
print(binary_search(ls, 10))
print(binary_search(ls, 33))