python解决汉诺塔问题极其简单

#!/usr/bin/env python3

# -*- coding: utf-8 -*-
#hanoi.py

def print_move(n, a, b):
    print(‘move %d %s => %s’ % (n, a, b))

def hanoi(n, a, b, c):
    if n == 1:
        print_move(n, a, c)
    else:
        hanoi(n-1, a, c, b)
        print_move(n, a, c)
        hanoi(n-1, b, a, c)




测试结果如下:

>>> python

>>> from hanoi import hanoi

>>> hanoi(3,’A’, ‘B’, ‘C’)
move 1 A => C
move 2 A => B
move 1 C => B
move 3 A => C
move 1 B => A
move 2 B => C
move 1 A => C

    原文作者: 汉诺塔问题
    原文地址: https://blog.csdn.net/GG_SiMiDa/article/details/61199276
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞