Python program Tower of Hanoi (modified)

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

You are tested for a test to locate the number of moves required to move a heap of plates starting with one peg then onto the next peg. Hang tight for a second, it sounds simple? How about we find 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 organizes as biggest is at the base and littlest is at the top. We are required to move this entire stack to another peg (absolute three pegs, two are unfilled at first) with thinking about the accompanying principle:

No bigger circle can be put over a little one.

Each circle in turn.

A circle can’t be moved to peg B legitimately. It must be moved to centre peg while moving from A to B or B to A.

The issue is looking simple however it’s definitely not. The manner in which we are going to handle it is recursion. The issue is straightforward 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 pile of one less disk(The biggest one) in addition to one stage.

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

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

So here is the code:

def hanoi(x):
    global repN
    repN += 1
    if x == 1:
        return 2
        return 3*hanoi(x-1) + 2
x = int(input("ENTER THE NUMBER OF DISKS: "))

global repN
repN =0

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


ENTER THE NUMBER OF DISKS: 14                                                                                                  
NUMBER OF STEPS:  4782968  : 14

Leave a Comment

error: Alert: Content is protected!!