Recursion - Tower of Hanoi - List based output

 # Recursion

# Tower of Hanoi 


def TowerOfHanoi(n , s, d, a):

if(n==0):

return


TowerOfHanoi(n-1, s, a, d)

ele = s.pop()

d.append(ele)

    

print(src,'-',aux,'-',dest)

TowerOfHanoi(n-1, a, d, s)

         

# Driver code

N = int(input("Enter number of disks : "))

src = [int(x) for x in range(N,0,-1)]

dest = []

aux = []

print("Src - Aux - Dest")

print(src,'-',aux,'-',dest)

TowerOfHanoi(N, src, dest, aux)


"""

Sample output

>python TOH_List.py

Enter number of disks : 3

Src - Aux - Dest

[3, 2, 1] - [] - []

[3, 2] - [] - [1]

[3] - [2] - [1]

[3] - [2, 1] - []

[] - [2, 1] - [3]

[1] - [2] - [3]

[1] - [] - [3, 2]

[] - [] - [3, 2, 1]


>python TOH_List.py

Enter number of disks : 4

Src - Aux - Dest

[4, 3, 2, 1] - [] - []

[4, 3, 2] - [1] - []

[4, 3] - [1] - [2]

[4, 3] - [] - [2, 1]

[4] - [3] - [2, 1]

[4, 1] - [3] - [2]

[4, 1] - [3, 2] - []

[4] - [3, 2, 1] - []

[] - [3, 2, 1] - [4]

[] - [3, 2] - [4, 1]

[2] - [3] - [4, 1]

[2, 1] - [3] - [4]

[2, 1] - [] - [4, 3]

[2] - [1] - [4, 3]

[] - [1] - [4, 3, 2]

[] - [] - [4, 3, 2, 1]

"""











No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu