


We saw that 15 moves are needed for a puzzle with 4 disks. In the example run of the extended versio of the code, To solve a puzzle with 1 disk, we need 1 move.įor 2 disks, 3 moves are needed. pop ( 0 )) write ( k, move + 1, nbr, apl, bpl, cpl ) # move nbr-1 disks from C to B, A is auxiliary move = hanoi ( nbr - 1, cpl, bpl, apl, k + 1, move + 1 ) return move pop ( 0 )) write ( k, move + 1, nbr, apl, bpl, cpl ) return move + 1 else : # move nbr-1 disks from A to C, B is auxiliary move = hanoi ( nbr - 1, apl, cpl, bpl, k + 1, move ) # move nbr-th disk from A to B bpl. """ if nbr = 1 : # move disk from A to B bpl. Writes the state of the piles after each move. The recursion depth is counted by k, move counts the number of moves. Writing a pile is then one single format conversion:ĭef hanoi ( nbr, apl, bpl, cpl, k, move ): """ Moves nbr disks from apl to bpl, cpl is auxiliary. We have to change the representation of the piles.Ī simple list to represent a pile no longer suffices. In the extended version with the print statements, Acting out the command of an ancient prophecy. This is the story (or one of many versions): Once there was an Indian temple in Kashi Vishwanath containing a large room with three time-worn posts in it, surrounded by 64 golden disks.

In the output above, the number of spaces before the move counterĮquals the depth of the tree of recursive calls. The 'Towers of Hanoi' riddle was introduced to the West by the French mathematician Edouard Lucas in 1883.
