#!/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