函数递归实例:斐波那契数列实例、汉诺塔问题、科赫雪花绘制实例

递归法则

#Caln!
def fact(n):
    if n==0:
        return 1
    else:
        return n*fact(n-1)

print(fact(15)) 

斐波那契数列 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)

print(f(5))

汉诺塔问题

count=0
def hanoi(n,src,dst,mid):#将圆盘从src搬到dst,mid是过渡
    global count
    if n==1:
        print('{}:{}->{}'.format(1,src,dst))
        count+=1
    else:
        hanoi(n-1,src,mid,dst)  #将第n-1个圆盘从src搬到mid
        print('{}:{}->{}'.format(n,src,dst)) #将第n个圆盘从src搬到dst
        count+=1  #完成1次
        hanoi(n-1,mid,dst,src)  #最后将第n-1个圆盘从mid搬到dst

hanoi(6,'a','b','c')
print(count)

运行效果如下:

D:\Anaconda3\python.exe D:/Python_pycharm_projects/yuyanseji_examples(20190404)/DIguiV0.py
1:a->c
2:a->b
1:c->b
3:a->c
1:b->a
2:b->c
1:a->c
4:a->b
1:c->b
2:c->a
1:b->a
3:c->b
1:a->c
2:a->b
1:c->b
5:a->c
1:b->a
2:b->c
1:a->c
3:b->a
1:c->b
2:c->a
1:b->a
4:b->c
1:a->c
2:a->b
1:c->b
3:a->c
1:b->a
2:b->c
1:a->c
6:a->b
1:c->b
2:c->a
1:b->a
3:c->b
1:a->c
2:a->b
1:c->b
4:c->a
1:b->a
2:b->c
1:a->c
3:b->a
1:c->b
2:c->a
1:b->a
5:c->b
1:a->c
2:a->b
1:c->b
3:a->c
1:b->a
2:b->c
1:a->c
4:a->b
1:c->b
2:c->a
1:b->a
3:c->b
1:a->c
2:a->b
1:c->b
63

科赫雪花绘制实例

#KochDrawV2.py
import turtle as t
def Koch(size,n):
    if n==0:
        t.fd(size)
    else:
        for angle in [0,60,-120,60]:
            t.left(angle)
            Koch(size/3,n-1)

def main():
    t.setup(600,600)
    t.pu()
    t.goto(-200,100)
    t.pd()
    t.pensize(2)
    level=3    #3阶科赫小雪花,阶数
    Koch(400,level)
    t.right(120)
    Koch(400,level)
    t.right(120)
    Koch(400,level)
    t.hideturtle()

main()

运行效果如下:
函数递归实例:斐波那契数列实例、汉诺塔问题、科赫雪花绘制实例_第1张图片

你可能感兴趣的:(Python程序设计)