Program for Tower of Hanoi using Python

Introduction

The task is to solve Tower of Hanoi problem using python programming. There are set of rules to follow while solving the problem:

  • At a time only one disk is allowed to be moved.
  • Only the uppermost disk is allowed to be moved.
  • Disks can only be placed on the top of larger disks.

Program

def TOH(disk , s, d, other):

    if disk==1:

        print("Place disk 1 from ",s,"to",d)

        return

    TOH(disk-1, s, other, d)

    print("Place disk",disk,"from",s,"to",d)

    TOH(disk-1, other, d, s)

ip_ndisk = int(input("Enter the number of disks: "))

TOH(ip_ndisk,'A','B','C')

Output

Program for Tower of Hanoi using Python Output

Explanation

The illustration of above program is :

Program for Tower of Hanoi using Python

Author

  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.