其他分享
首页 > 其他分享> > 12_迭代和递归

12_迭代和递归

作者:互联网

求一个数的阶乘
# 迭代方法实现
def factIter(n):
    result = n
    for i in range(1, n):
        result *= i
    return result
print(factIter(10))

# 递归方法实现
def funC(n):
    if n == 1:
        return 1
    else:
        return n * funC(n-1)
print(funC(10))
斐波那契数列
# 迭代方法实现
def fibIter(n):
    a = 1
    b = 1
    c = 1
    while n > 2:
        c = a + b
        a = b
        b = c
        n -= 1
    return c
print(fibIter(12))
# 递归方法实现
def fibRecur(n):
    if n == 1 or n == 2:
        return 1
    else:
        # print(fibRecur(n - 1))
        # print(fibRecur(n - 2))
        return fibRecur(n-1) + fibRecur(n-2)
print(fibRecur(12))
汉诺塔
def hanoi(n, x, y, z):
    if n == 1:
        print(x, "移动到》》》", z)   # 如果只有 1 层,直接将金片从 x 移动到 z
    else:
        hanoi(n - 1, x, z, y)     # 将x上的n - 1 个金片移动到y
        print(x, "移动到》》》", z)  # 将最底下的金片从 x 移动到 z
        hanoi(n - 1, y, x, z)  # 将y上的n - 1 个金片移动到z
n = int(input("请输入汉诺塔的层数:"))
print(hanoi(n, "A", "B", "C"))

 

 

标签:12,return,迭代,递归,hanoi,fibRecur,金片,print,def
来源: https://www.cnblogs.com/tuyin/p/16552964.html