递归函数
例如计算阶乘n! = 1 x 2 x 3 x ... x n
,用函数fact(n)
表示:
fact(n) = n! = 1 x 2 x 3 x ... x (n-1) x n = (n-1)! x n = fact(n-1) x n
显然fact(n)=n x fact(n-1),但当n = 1时,需要做特殊处理
递归函数定义形式如下:
def fact(n)
if n == 1:
return 1
return n * fact(n-1)
当n取值很大时,递归函数调用时会引起栈溢出,为了解决栈溢出问题,通常通过尾递归优化。
【尾递归是指,在函数返回的时候,调用自身本身,并且,return语句不能包含表达式】:
#尾递归定义形式
def fact(n):
return fact_iter(n, 1)
def fact_iter(num, product):
if num == 1:
return product
return fact_iter(num - 1, num * product)
-------------------------------------------------------------------------------------------
#执行过程
----->fact(5)
----->fact(5,1)
----->fact(4,5)
----->fact(3,20)
----->fact(2,60)
----->fact(1,120)
----->120
练习【利用递归函数移动汉诺塔】
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def move(n,a,b,c):
if n == 1:
print('move',a,'--->',c)
else:
move(n-1, a, c, b)
move(1,a,b,c)
move(n-1,b,a,c)
move(4,'A','B','C')
参考资料
来源:oschina
链接:https://my.oschina.net/u/4280865/blog/4210122