This code snippet implements a solution for the Tower of Hanoi problem using recursion. The Tower of Hanoi is a classic problem in computer science and mathematics. The goal is to move a stack of discs from one peg to another, using an auxiliary peg, following specific rules.
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")
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
move(disc, source, destination, aux)
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)
disc
: The number of discs to move.source
: The peg from which discs are moved.destination
: The peg to which discs are moved.aux
: The auxiliary peg used for intermediate moves.disc
is greater than 0. If disc
is 0 or less, the function does nothing (implicitly returns None
).move(disc - 1, source, aux, destination)
disc - 1
discs from the source
peg to the aux
peg, using the destination
peg as auxiliary.source
peg to the destination
peg.move(disc - 1, aux, destination, source)
disc - 1
discs from the aux
peg to the destination
peg, using the source
peg as auxiliary.move(4, "left", "middle", "rigth")
move
function is called with 4
discs, moving from the “left” peg to the “middle” peg, using the “right” peg as auxiliary.move(4, "left", "middle", "right")
The Tower of Hanoi puzzle involves three pegs and a number of discs of different sizes. The rules are:
For move(4, "left", "middle", "right")
, the function will:
This process involves multiple recursive calls to break down the problem into smaller subproblems until the base case is reached.