""" hanoi.py Towers of Hanoi in python. Based on perl program by DigitalKitty (Katie) on perlmonks.org, node 400359 on 10/20/2004 Jim Mahoney, Nov 2008, GPL A B C | | | --- 1 | | ----- 2 | | ------- 3 | | ============================================ For this stack with 3 disks, the moves would be disk 1 moves A to B disk 2 moves A to C disk 1 moves B to C disk 3 moves A to B disk 1 moves C to A disk 2 moves C to B disk 1 moves A to B """ def move_disks(n, start='A', end='B', extra='C'): """Return string of moves moving n disks start one column to another. >>> move_disks(1) ' disk 1 moves A to B \\n' >>> move_disks(2) ' disk 1 moves A to C \\n disk 2 moves A to B \\n disk 1 moves C to B \\n' """ format = " disk %i moves %s to %s \n" if n == 1: return format % (1, start, end) # At top? Just move it. else: # Here's the heart of it. The idea is # 1) move the top n-1 disks to the extra column, then # 2) move the biggest disk n from 'start' to 'end', then # 3) move the top n-1 disks again, this time from 'extra' to 'end'. return move_disks(n-1, start, extra, end) + \ format % (n, start, end) + \ move_disks(n-1, extra, end, start) def hanoi(): n_disks = input("Number of disks? ") print "The moves are: " print move_disks(n_disks), if __name__=="__main__": from doctest import testmod testmod() hanoi()