函数递归python以及汉诺塔问题

# def fact(n):
#     if n==1:
#         return 1
#     return n*fact(n-1)
# print(fact(1000))
import sys
sys.setrecursionlimit(1000000)
def fact(n):
    return fact_iter(n,1)

def fact_iter(num,product):
    if num==1:
        return product
    return fact_iter(num-1,num*product)
print(fact(1000))#防止递归栈溢出,使用尾递归,每次进入一个函数调用,栈帧就加一,返回就减一,
#尾递归是指,函数返回时,调用自身,并且return不能返回包含表达式
#汉诺塔
def move(n, a, buffer, c):
#可以通过isinstance来限定n的类型,最好限制n的大小。
    if(n == 1):
        print(a,"->",c)
        return
    move(n-1, a, c, buffer)#通过c作为缓冲区,把a上的n-1个盘子传到b上
    move(1, a, buffer, c)#把a上最底下的盘子弄到c上
    move(n-1, buffer, a, c)#把b上的盘子通过a缓冲到c上
move(3, "a", "b", "c")

猜你喜欢

转载自blog.csdn.net/qq_34211771/article/details/54894717