美文网首页
函数练习-汉诺塔

函数练习-汉诺塔

作者: 木果渣 | 来源:发表于2017-12-13 23:48 被阅读0次

分三次,最后一次才正确
take 1 :

def hanoi_tower(n, a, b, c):
    if n == 1:
        print(a, '-->', c)
    elif n % 2 == 0:
        print(a, '-->', b)
        hanoi_tower(n-1, b, a, c)
        print(a, '-->', c)
    else:
        print(a, '-->', c)
        hanoi_tower(n-1, a, b, c)
        print(c, '-->', a)

hanoi_tower(3, 'A', 'B', 'C')

take2:

print('hello hanoi tower!')
def hanoi_tower(n, a, b, c):
    if n == 1:
        print(a, '-->', c)
    else:
        print(a, '-->', b)
        hanoi_tower(n-1, a, b, c)
        print(b, '-->', c)
hanoi_tower(3, 'A', 'B', 'C')
    

take 3:

def hanoi_tower(n, a, b, c):
    if n == 1:
        print(a, '-->', c)
    else:
        hanoi_tower(n-1, a, c, b)
        print(a, '-->', c)
        hanoi_tower(n-1, b, a, c)
        
hanoi_tower(4, 'A', 'B', 'C')

相关文章

网友评论

      本文标题:函数练习-汉诺塔

      本文链接:https://www.haomeiwen.com/subject/fletwxtx.html