Python program for Tower of Hanoi

Here, we are going to actualize a python program for Tower of Hanoi.

You are tested for a test to locate the number of moves required to move a pile of circles starting with one peg then onto the next peg. Hang tight for a second, it sounds simple? We should discover are what is happening and in this article, we are presenting a section of “TOWER OF HANOI”.

You are given with a pile of n circles on a peg orchestrates as biggest is at the base and littlest is at the top. We are required to move this entire stack to another peg (complete three pegs, two are unfilled at first) with thinking about the accompanying guideline:

No bigger circle can be set over a little one.

Each circle in turn.

The issue is looking simple however it’s most certainly not. The manner in which we are going to handle it is recursion. The issue is basic when you see it from recursion viewpoint.

Key: The quantity of steps required to move the stack is actually equivalent to the twice of steps for moving the heap of one less disk(The biggest one) in addition to one stage.

    Consider the case of shifting one disk : T(1) = 1
    Consider the case of shifting two disk : T(2) = 2*T(1) + 1 = 3
    Consider the case of shifting three disk : T(3) = 2*T(2) + 1 = 7
    T(n) = 2*T(n-1) + 1

Actualizing this recipe now in our python program is our next objective of tackling this.

So here is the code:

def hanoi(x):
    if x == 1:
        return 1
        return 2*hanoi(x-1) + 1

x = int(input("ENTER THE NUMBER OF DISKS: "))

print('NUMBER OF STEPS: ', hanoi(x))



Leave a Comment

error: Alert: Content is protected!!