递归函数
- 递归:函数间接或直接调用自己
- 递归分两个过程
- 往下调用,分解的过程
- 往上回溯,综合的过程
- 递归需要注意
- 一定要有结束条件
- 是以资源换取编写速度的算法
# 递归函数案例
def funa(name):
print("My name is " + \
name.title() + \
".")
def funb(fruit):
funa('jack')
print("My favorite fruit is " + \
fruit + \
".")
funb('apple')
My name is Jack.
My favorite fruit is apple.
一:阶乘
- 函数表达式
- f(n) = 1 (n=1)
- f(n) = n * f(n-1) (n>=2)
# 递归函数调用
def fun_a(n):
print(n)
# 一定要右结束条件
if n == 1:
return 1
return n * fun_a(n-1)
n = 3
re = fun_a(n)
print("f(" ,n, "):", re)
二:斐波那契数列
- 函数表达式:
- f(n) = 1 n={1, 2}
- f(n) = f(n-1) + f(n-2) n>=3
- 数学定义自行查找
# 斐波那契数列
def fib(n):
# 结束条件
if n == 1 or n == 2:
return 1
return fib(n-1) + fib(n-2)
n = 10
re = fib(n)
print("f(", n, "):", re)
f( 10 ): 55
三:汉诺塔
- 规定:
- 把圆盘从下面开始按大小顺序重新摆放在另一根柱子上
- 小圆盘上不能放大圆盘
- 在三根柱子之间一次只能移动一个圆盘
a = 'A'
b = 'B'
c = 'C'
def hano(a, b, c, n):
if n == 1:
print("{}-->{}".format(a,c))
return None
if n == 2:
print("{}-->{}".format(a,b))
print("{}-->{}".format(a,c))
print("{}-->{}".format(b,c))
return None
# 不管多少个盘子
# 都将n-1个盘子从a借助c移到b
hano(a, c, b, n-1)
# 再将最后一个盘子从a移到c
print("{}-->{}".format(a,c))
# 剩下的n-1个盘子
hano(b, a, c, n-1)
hano(a, b, c, 4)
A–>B
A–>C
B–>C
A–>B
C–>A
C–>B
A–>B
A–>C
B–>C
B–>A
C–>A
B–>C
A–>B
A–>C
B–>C