< !- START disable copy paste -->

Sunday, 25 February 2018

Towers of Hanoi using python

This is Towers of Hanoi program. This concept uses three towers namely source, intermediate and destination. The concept is to place the disks from source tower to destination tower. Smaller disk should be always on larger disk vice versa is not possible. The order of disks on source tower and on destination tower should be same. This concept uses recursion.

Source code:

def hanoi(n,s,i,d):
    if n==1:
        print("move 1 disk from",s,"to",d)
        return
    else:
        hanoi(n-1,s,d,i)
        hanoi(1,s,i,d)
        hanoi(n-1,i,s,d)

n=int(input("enter no of disks"))
hanoi(n,"s","i","d")

 
Output:

Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
enter no of disks3
move 1 disk from s to d
move 1 disk from s to i
move 1 disk from d to i
move 1 disk from s to d
move 1 disk from i to s
move 1 disk from i to d
move 1 disk from s to d
>>>
Now my new Blog on Fundamentals of Python can be found at https://fundamentalsofpython.blogspot.com/2020/02/list-manipulations.html

No comments:

Post a Comment

Reverse Doubly Linked List

Source Code class Node:    def __init__(self,data):         self.data = data         self.left = None         self.right = None cla...