递归

1.吓得我抱起了。。。

print('吓得我抱起了',end='')
def fun1(n):
    if n == 0:
        print('我的小鲤鱼',end='')
    else:
        print('抱着',end='')
        fun1(n-1)
        print('的我',end='')


fun1(3)

2.等差数列求和

sum = 0

def func1(i):
    global sum
    if i >0:
        sum = i + func1(i-1)
    return sum
sum = func1(5)
print(sum)

3.汉诺塔问题

t = 0
def fun1(n,a,b,c):
    global t
    if n>0:
        fun1(n-1,a,c,b)
        t+=1
        print('#%d:%s-->%s'%(n,a,c))
        fun1(n-1,b,a,c)


fun1(8,'a','b','c')
print(t)

 

原文地址:https://www.cnblogs.com/ldq1996/p/8394548.html