Q:

Python program Tower of Hanoi (modified)

belongs to collection: Python basic programs

0

The problem is looking easy but it's not. The way we are going to tackle it is recursion. The problem is simple when you see it from recursion perspective.

Key: The number of steps required to shift the stack is exactly equal to the twice of steps for shifting the stack of one less disk(The largest one) plus one step.

    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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

So here is the code:

def hanoi(x):
    global repN
    repN += 1
    if x == 1:
        return 2
    
    else:
        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)

Output:

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to convert Centimeter to Inches... >>
<< Python program to find the variance...