Bootstrap

用递归法求解斐波那契数列(Python)

1、[1,1,2,3,5,8,13......] 

递归加缓存


def fibs(i, buffer):  # 返回斐波那契数列第i个数
    # 定义递归边界
    if i in (1, 2):
        buffer[i] = 1
        return 1  # 上面就是递归边界
    elif i in buffer:
        return buffer[i]
    else:
        result = fibs(i-1, buffer) + fibs(i-2, buffer)  # 递归表达式
        buffer[i] = result
        return result




if __name__ == '__main__':
    for i in range(1,10):
        buffer = {}  # 递归加缓存
        print(fibs(i, buffer))


 

;