deffunca(n):print("I am xiner")deffuncb(n):
funca(100)print("I am miner")
funcb(100)
I am xiner
I am miner
# func_a 表示计算阶乘deffunc_a(n):print(n)# 递归一定要有结束条件if n ==1:return1return n * func_a(n-1)
r = func_a(5)print("f(5) = ",r)
5
4
3
2
1
f(5) = 120
# 递归必须有结束条件,否则会死deffun_b(n):print(n)return n * fun_b(n -1)
fun_b(50)
RecursionError Traceback (most recent call last)
<ipython-input-9-ff1e56342032> in <module>()
3 print(n)
4 return n * fun_b(n - 1)
----> 5 fun_b(50)
<ipython-input-9-ff1e56342032> in fun_b(n)
2 def fun_b(n):
3 print(n)
----> 4 return n * fun_b(n - 1)
5 fun_b(50)
... last 1 frames repeated, from the frame below ...
<ipython-input-9-ff1e56342032> in fun_b(n)
2 def fun_b(n):
3 print(n)
----> 4 return n * fun_b(n - 1)
5 fun_b(50)
RecursionError: maximum recursion depth exceeded while calling a Python object
# 斐波那契数列# 数学定义deffib(n):if n ==1or n ==2:return1else:return fib(n -1)+ fib(n -2)
r = fib(10)print(r)
55
# 汉诺塔
a ='A'
b ='B'
c ='C'defhano(a,b,c,n):if n ==1:print("{}->{}".format(a,c))returnNoneif n ==2:print("{}->{}".format(a,c))print("{}->{}".format(a,b))print("{}->{}".format(b,c))returnNone
hano(a,c,b,n -1)print("{}->{}".format(a,c))
hano(b,a,c,n -1)#只有一个盘子
hano(a,b,c,1)print("---------------")# 两个盘子
hano(a,b,c,2)print("---------------")#5个盘子
hano(a,b,c,5)