Hackbright Code Challenges

Towers of Hanoi: Solution

Towers of Hanoi: Solution

Problem

Towers of Hanoi

Challenge

Harder

Concepts

Recursion, Stacks

Download

hanoi-solution.zip


def move(n, source, helper, target):
    """Move disks from one stack to another.

    Move `n` disks from `source` to `target`, using the
    middle stack, `helper`, as a temporary place.
    Movements must follow Hanoi rules.

    For example, it's easy to move one::

        >>> s1 = Stack([1])
        >>> s2 = Stack()
        >>> s3 = Stack()
        >>> move(1, s1, s2, s3)
        >>> s1, s2, s3
        ([], [], [1])

    Moving three::

        >>> s1 = Stack([3, 2, 1])
        >>> s2 = Stack()
        >>> s3 = Stack()
        >>> move(3, s1, s2, s3)
        >>> print((s1, s2, s3))
        ([], [], [3, 2, 1])
    """

    # START SOLUTION

    if n > 0:
        move(n - 1, source, target, helper)

        target.push(source.pop())

        move(n - 1, helper, source, target)