Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in

Posted on

Python Solve the towers of hanoi problem

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

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


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

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

hanoi(3, "A", "B", "C")
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)