递归二进制搜索Python 3打印解决方案,但未返回

时间:2018-08-18 17:10:28

标签: python function recursion search binary

from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

如果我写了return(m)而不是print(m),然后尝试打印它返回None的函数,我不明白为什么。 有人可以解释吗? 谢谢

1 个答案:

答案 0 :(得分:0)

def binarySearch( a, l, r, num ):

    m = (l+r) // 2

    if l < r:

        if num == a[m]:
            return m

        elif num < a[m]:
            return binarySearch(a, l, m, num)

        else:
            return binarySearch(a, m+1, r, num)
    else:
        return  -1

 # If return statement with the thing that need to be return is not mentioned explicitly  by default we get None 

'''
--tested using
for i in range(0,8):
    print('result for item', i ,binarySearch( [0,1,2,5,7], 0, 5,i )) 
'''