python方法解决斐波那契数列及阶乘和

用递归解决斐波那契数列

def fib(n):
    lt = []
    for i in range(n):
        if i == 0 or i == 1:
            lt.append(1)
        else:
            lt.append(lt[i - 2] + lt[i - 1])
    return lt


print(fib(9))

递归方法解决阶乘和

# f(n) = 1! + 2! + ... + (n-1)! + n!
# f(n) = f(n-1) + n!
# f(n) = f(n-1) + n * (n-1)!
# f(n) = f(n-1) + n * (f(n-1) - f(n-2))
# f(n) = (n+1) * f(n-1) - n * f(n-2)
def jiechenghe(n):
    if n == 1:
        return 1
    elif n == 2:
        return 3
    return (n+1) * jiechenghe(n-1) - n * jiechenghe(n-2)


你可能感兴趣的:(学习)