python中的递归小实例

时间:2021-08-06 17:00:33

#1.n!

def fact(n):
if n == 0:
return 1
else:
return n*fact(n-1)
print(fact(10))
#2.斐波那契数列F(n)=F(n-1)+F(n-2)
def f(n):
if n == 1 or n == 2:
return 1
else:
return f(n-1)+f(n-2)
#3汉诺塔问题
count = 0
def hanoi(n,src,dst,mid):
global count
if n == 1:
print("{}:{}->{}".format(1,src,dst))
count += 1
else:
hanoi(n-1,src,mid,dst)
print("{}:{}->{}".format(n, src, dst))#第n个圆盘从第src位置移动到dst位置
count += 1
hanoi(n-1,mid,dst,src)
hanoi(3,"A","C","B")
print(count)
#4
#字符串反转s[::-1]
s = "python"
def reverse (s):
if s == "":
return s
else:
return reverse (s[1:])+s[0]
print(reverse(s))