How to Solve the Tower of Hanoi Puzzle Using a For Loop in Python?

Estimated read time 2 min read

The Tower of Hanoi puzzle is a classic problem in computer science and mathematics that involves moving a stack of disks from one peg to another, using a third peg as a temporary buffer, such that no larger disk is ever placed on top of a smaller disk.

Here is an example of solving the Tower of Hanoi puzzle using a for loop in Python:

def tower_of_hanoi(n, source, dest, temp):
    for i in range(1, 2**n):
        if i & i-1:
            if i % 3 == 1:
                move_disk(source, dest)
            elif i % 3 == 2:
                move_disk(source, temp)
                move_disk(temp, dest)
            if n % 2 == 0:
                move_disk(source, temp)
                move_disk(source, dest)

Here, n represents the number of disks, source represents the starting peg, dest represents the destination peg, and temp represents the temporary buffer peg. The move_disk function is not defined in this example, but it can be a simple function that takes two arguments representing the source and destination pegs and prints a message indicating that a disk has been moved from the source peg to the destination peg.

The for loop iterates 2^n - 1 times, where n is the number of disks. The if i & i-1 condition checks if the current iteration number is a power of 2 or not. If it is, then we are at the start of a new round of moves, and we need to determine whether to move the top disk from the source peg to the dest peg, the source peg to the temp peg, or the temp peg to the dest peg. If it’s not a power of 2, then we are in the middle of a round of moves, and we simply move the top disk from the source peg to the temp peg if n is even, or from the source peg to the dest peg if n is odd.

Note that this implementation assumes that the number of disks is less than or equal to the maximum integer representable in Python, which is sys.maxsize on most systems.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply