1、递归函数的定义:
在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。
2、下面分别用阶乘和斐波那契数列举例
1.阶乘就是递归函数的一个典型的例子,阶乘n! = 1 x 2 x 3 x ... x n,用函数f(n)表示
1 #阶乘 2 3 def f(n): 4 if n==1: 5 return 1 #当n为1时,返回1 6 7 r=n*f(n-1) #当n为n时,返回1 x 2 x 3 x ... x (n-1) x n 8 return r 9 10 print(f(5)) #当n为5时,返回1 x 2 x 3 x 4 x5 =120
2.斐波那契数列也是一个典型的例子,斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368·····,这个数列从第2项开始,每一项都等于前两项之和
1 #斐波那契数列 2 3 #这里定义一个函数f,里面三个函数,x表示斐波那契数列的长度,我们这里定义x到10截止,a1表示斐波那契数列的第1个元素,a2为第2个元素 4 5 def f(x,a1,a2): 6 7 print (x,a1) #这里每次打印输出x,a1,这里可以看成是x为斐波那契函数的长度,a1为第x个元素的值 8 9 if x == 10: 10 return "到底" #让x最大的值为10 11 12 a3=a1+a2 #前两项数之和为第三个数 13 r = f(x+1,a2,a3) 14 return r 15 16 ret=f(1,0,1) 17 18 print(ret)
上面代码的第10个元素为34