Python Code Example: tower of hanoi (recursive)

This is a Python function move that implements the solution for the Towers of Hanoi problem. The Towers of Hanoi is a classic problem that involves moving a series of discs from one peg to another, subject to the constraint that larger discs cannot be placed on smaller discs.

The move function takes four parameters:

  • disc: the number of discs to be moved
  • source: the name of the source peg
  • destination: the name of the destination peg
  • aux: the name of the auxiliary peg

The function uses recursion to move the discs from the source peg to the destination peg using the auxiliary peg. The base case of the recursion is when disc is equal to 0, in which case the function does nothing. In other cases, the function first calls itself with disc - 1 and the source peg, auxiliary peg, and destination peg swapped. This step moves the top disc - 1 discs from the source peg to the auxiliary peg. Then, the function prints a message indicating that the disc-th disc is moved from the source peg to the destination peg. Finally, the function calls itself again with disc - 1 and the auxiliary peg, destination peg, and source peg swapped. This step moves the remaining disc - 1 discs from the auxiliary peg to the destination peg.

In the code, the function is called with 4, “left”, “middle”, and “right” as the parameters, which will result in a series of moves that solves the Towers of Hanoi problem with 4 discs.

def move(disc, source, destination, aux):
    if disc > 0:
        move(disc - 1, source, aux, destination)
        print("Disc " + str(disc) + ": move from " + str(source) + " to " + str(destination))
        move(disc - 1, aux, destination, source)


move(4, "left", "middle", "rigth")
Output
Disc 1: move from left to rigth
Disc 2: move from left to middle
Disc 1: move from rigth to middle
Disc 3: move from left to rigth
Disc 1: move from middle to left
Disc 2: move from middle to rigth
Disc 1: move from left to rigth
Disc 4: move from left to middle
Disc 1: move from rigth to middle
Disc 2: move from rigth to left
Disc 1: move from middle to left
Disc 3: move from rigth to middle
Disc 1: move from left to rigth
Disc 2: move from left to middle
Disc 1: move from rigth to middle