I am currently following a course and we were given to write a function for the Towers of Hanoi mathematical puzzle.
After following up some videos on youtube about it, I have compiled the following function:
def hanoi(n , source, target, spare):
if n == 1:
print("Move disk 1 from", source, "to", target)
else:
hanoi(n-1, source, spare, target)
print ("Move disk", n, "from", source, "to", target)
hanoi(n-1, spare, target, source)
Let's say I call this function as hanoi(3, "source", "target", "spare")
The output that I get is:
Move disk 1 from source to target
Move disk 2 from source to spare
Move disk 1 from target to spare
Move disk 3 from source to target
Move disk 1 from spare to source
Move disk 2 from spare to target
Move disk 1 from source to target
A friend recommended me to write down the code on paper in order to understand it but I fail to understand:
- why is the function running the
if
clause when my n equals 3? - how is the computer actually running the program? What is the logic of going through the conditional statements?
This baffles me also due to the fact that I put that
print
statement in between (because placing it in another place wouldn't have printed the right results)
Thanks a lot for your help and time!
EDIT: The Towers of Hanoi means having (by default) 3 poles. One pole would be the source
pole (where the n disks would be originally placed), 2nd pole is the spare
pole used as a helper and the 3rd pole is the target
pole (where all the n disks would be originally placed). I used these variables to represent the poles and to be able to show the movement of the disks
The rules are: you can move 1 disk at a time and you cannot place a bigger disk on a smaller disk.