Python递归

递归基础

def fact(n):
    if n==1:
        return 1
    return n*fact(n-1)#递归调用自己,形成递归函数
print(fact(20))
print(fact(4))

进行递归优化

def fact_1(m):
    return fact_2(m,1)
def fact_2(num,product):
    if num==1:
        return product
    return fact_2(num-1,num*product)    #尾递归的使用方法,能够节约大量空间
print(fact_1(4))
print(fact_1(20))

用递归函数实现汉诺塔的方法:

'''
i=int(input('piease input a number:'))
def move(i,a='A',b='B',c='C'):
    if i==1:
        print(a,'--->',c)
    else:
        move(i-1,a,c,b)#把n-1从A移动到b
        #print(a,'-->',c)#这句话有下面的写法
        move(1,a,b,c)#把最下面一个大的移动到C
        move(i-1,b,a,c)#把B上的n-1移动到C
move(i)
'''

hanoi优化

K=0
l=int(input('please input a number:'))
def move_1(n,o_1,p_1,q_1):
    global K#python中全局变量的使用方法
    K+=1
    print('第%d步:%c--->%c' % (K,o_1,q_1))
    #print(o_1,'--->',q_1)
def hanoi(l,o,p,q):
    if l==1:
        move_1(1,o,p,q)
    else:
        hanoi(l-1,o,q,p)
        move_1(1,o,p,q)
        hanoi(l-1,p,o,q)
hanoi(l,'A','B','C')