Hackerss.com

hackerss
hackerss

Posted on

Python Solve the towers of hanoi problem


def hanoi(n, source, helper, target):
    """
    Solve the towers of hanoi problem.

    Parameters
    ----------
    n : int
        Number of disks.
    source : str
        Source tower.
    helper : str
        Helper tower.
    target : str
        Target tower.

    Returns
    -------
    None
    """

    if n == 1:
        print("Move disk 1 from {} to {}".format(source, target))
        return

    hanoi(n-1, source, target, helper)
    print("Move disk {} from {} to {}".format(n, source, target))
    hanoi(n-1, helper, source, target)


#example
hanoi(3, "A", "B", "C")
#output
"""
Move disk 3 from A to C
Move disk 2 from A to B
Move disk 1 from A to C
Move disk 3 from B to A
Move disk 1 from B to C
Move disk 2 from A to C
"""
Enter fullscreen mode Exit fullscreen mode

Top comments (0)