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

Leave a comment

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