How to add counter in this code to display number of steps?

105 Views Asked by At
def toh(N, fromm=1, to=3, aux=2):
    # Your code here

    if N == 1:
        print('move disk', N, 'from rod', fromm, 'to rod', to)
        return
    else:
        toh(N - 1, fromm, aux, to)
        print('move disk', N, 'from rod', fromm, 'to rod', to)
        toh(N - 1, aux, to, fromm)



#Driver code Starts

import math
def main():
    T = int(input())
    while(T > 0):
        N = int(input())
        print(toh(N, 1, 3, 2))

        T -= 1

if __name__ == "__main__":
    main()

#Driver code Ends

Remember Do not change driver code

test cases are as follows:

N = 2
expected Output:
move disk 1 from rod 1 to rod 2
move disk 2 from rod 1 to rod 3
move disk 1 from rod 2 to rod 3
3

here 3 is "total number of steps taken" which i want to add in this code

My output:                  
For Input:2
                  
move disk 1 from rod 1 to rod 2             
move disk 2 from rod 1 to rod 3                 
move disk 1 from rod 2 to rod 3               
None
1

There are 1 best solutions below

0
On

Finally i did this

def toh(N, fromm=1, to=3, aux=2, count=0):
    # Your code here

    if N == 1:
        print('move disk', N, 'from rod', fromm, 'to rod', to)
        return count + 1
    else:
        toh(N - 1, fromm, aux, to)
        print('move disk', N, 'from rod', fromm, 'to rod', to)
        toh(N - 1, aux, to, fromm)
        return count + (2**N-1)

        

# Driver code Starts

import math
def main():
    T = int(input())
    while(T > 0):
        N = int(input())
        print(toh(N, 1, 3, 2))

        T -= 1

if __name__ == "__main__":
    main()

# Driver code Ends