Tower of Hanoi

This problem might be the most famous example for teaching Recursion, and here is a simple example in Python.


def hanoi(n, source="A", temp="B", drain="C"):
    if n > 0:
        hanoi(n-1, source, drain, temp)
        print("Move a Disc from ",source, " to ", drain)
        hanoi(n-1, temp, source, drain)

if __name__ == '__main__':
    hanoi(int(input('How many disks you wanna play? ')))

Note:

if __name__ == “main”:

is used to execute some code only if the file was run directly, and not imported.

An alternative version:

def hanoi(n, source="A", temp="B", drain="C"):
    if n==1:
        print("Move a Disc from ",source, " to ", drain)
        
    else:
        hanoi(n-1, source, drain, temp)
        print("Move a Disc from ",source, " to ", drain)
        hanoi(n-1, temp, source, drain)
        
if __name__ == '__main__':        
hanoi(int(input('How many disks you wanna play? ')))

An useful demonstration provided by dynamic drive is able to know this game through animation.

http://www.dynamicdrive.com/dynamicindex12/towerhanoi.htm

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s