递归的入门

什么是递归
递归基本是一个函数,在这个函数中,间接或者直接的调用本身
递归的数学表达:
f(x) = g(f(x - 1)),其中,求解递归的过程就是找出g(x)
定义递归的关键:
1)找出递推公式g(x);
2)找出终止条件;
下面分别用两个例子进行说明:
#求阶乘

def factorial(n):
if n == 0 :
return 1;
else:
return n * factorial(n - 1);
#斐波那契数列
"""
f(x) = f(x - 1) + f(x - 2) x>=2
x x < 2
"""
def fibonacci_sequence(n):
if n < 2:
return n
else:
return fibonacci_sequence(n - 1) + fibonacci_sequence(n -2)
原文地址:https://www.cnblogs.com/tomorrow-hope/p/13782485.html