Hanoi Towers Explanation

I start with python and want to know what the role of the if in this Towers of Hanoi function is:

 def hanoi(ndisks, startPeg=1, endPeg=3): if ndisks: hanoi(ndisks-1, startPeg, 6-startPeg-endPeg) print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg) hanoi(ndisks-1, 6-startPeg-endPeg, endPeg) hanoi(ndisks=4) 
+4
source share
1 answer

A recursive algorithm requires a terminal condition, which is usually the simplest case of an algorithm. For Towers of Hanoi, the easiest case is when there are zero disks to move, do nothing.

In Python, one condition for β€œfalsity” is any numeric version of zero, so technically, if someone passed a negative number to your algorithm, it fails, so it would be better to check if ndisks > 0 . This stops the recursion when ndisks == 0.

If to move a positive number (n) of disks, a recursive algorithm:

  • Move the n-1 drives from the start of the binding to a different binding.
  • Move drive n th from start to finish.
  • Move n-1 drives from the β€œother” binding to the end.

The description above describes the rest of your code, with the terminal status being a null drive.

+4
source

All Articles