递归

一、斐波那契数列

def fibo(n):
    if n <= 1:
        return n
    else:
        return (fibo(n-1)+fibo(n-2))

print(fibo(13))
def fibonacci(n):
    """
    递归函数
    输出斐波那契数列
    :param n:
    :return:
    """

def fibonacci(n):
    if n <= 1:
        return n
    else:
        return (fibonacci(n-1) + fibonacci(n-2))

while 1:
    input_value = int(input('您要输出几项?'))

    if input_value <= 0:
        print('请输入正数')
    else:
        print('Fibonacci Sequence:')
        for i in range(1,input_value):
            print(fibonacci(i))

二分法

def binary_search(li,val):
    low = 0
    high = len(li) - 1
    while low <= high:
        mid = (low + high) // 2
        if li[mid] > val:
            high = mid - 1
        elif li[mid] < val:
            low = mid + 1
        else:
            return mid
    else:
        return -1


li = list(range(0,1000000,2))
t = binary_search(li,3892)

你可能感兴趣的:(递归)