Python函数之递归(用递归实现二分查找)

递归:简单来说就是引用(或者调用)自身的意思。

#阶乘
def factorical(n):
    result=n
    for i in range(1,n):
        result *=i
    return result
print(factorical(12))


输出:
479001600

代码实现二分查找法:

#实现二分查找法
def search(sequence, number, lower=0, upper=None):
    if upper is None: upper = len(sequence) - 1  #如果不加这两句会出现‘TypeError: search() missing 2 required positional arguments: 'lower' and 'upper'’,这种错误
    if lower == upper:
        assert number == sequence[upper]
        return upper
    else:
        middle = (lower + upper) // 2
        if number > sequence[middle]:
            return search(sequence, number, middle + 1, upper)
        else:
            return search(sequence, number, lower, middle)


seq = [34, 67, 8, 123, 4, 100, 95]
seq.sort()
print(seq)
print(search(seq, 34))


输出:
[4, 8, 34, 67, 95, 100, 123]
2

 

你可能感兴趣的:(python,数据结构,算法)