python 递归函数
斐波那契数列
1,1,2,3,5,8 #fib(6) = fib(5) + fib(4)
def fib(n): if n == 1 or n==2: return 1 return fib(n-1) + fib(n-2) print(fib(50))
另一种方法
def fib(n,a=1,b=1): if n==1 : return a return fib(n-1,b,a+b) print(fib(5))
用生成器
def fib(n): prev,curr = 0,1 while n > 0: n -= 1 yield curr prev,curr = curr,curr + prev print([i for i in fib(10)])
阶乘
3!= 3*2*1
def fac(n): if n == 1 : return 1 return n * fac(n-1) print(fac(100))