Skip to content

Q5: Towers of Hanoi

python
def print_move(origin, destination):
    """Print instructions to move a disk."""
    print("Move the top disk from rod", origin, "to rod", destination)

def move_stack(n, start, end):
    """Print the moves required to move n disks on the start pole to the end
    pole without violating the rules of Towers of Hanoi.

    n -- number of disks
    start -- a pole position, either 1, 2, or 3
    end -- a pole position, either 1, 2, or 3

    There are exactly three poles, and start and end must be different. Assume
    that the start pole has at least n disks of increasing size, and the end pole is either empty or has a top disk larger than the top n start disks.
    """
    assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, "Bad start/end"
    "*** YOUR CODE HERE ***"
    mid = [x for x in range(1, 4) if x != start and x != end][0]
    if n == 1:
        print_move(start, end)
        return
    elif n == 2:
        move_stack(1, start, mid)
        move_stack(1, start, end)
        move_stack(1, mid, end)
        return 
    else:
        move_stack(n-1, start, mid)
        move_stack(1, start, end)
        move_stack(n-1, mid, end)