Implementing the Hanoi method under Python

Source: Internet
Author: User
Hanoi is an ancient Indian legend of educational toys. The movement of Hanoi can also be seen as a recursive function.

We have a column numbered A, B, C, and all the discs from a to C can be described as:
If a has only one disc, it can be moved directly to C;
If a has N disks, it can be seen as a has 1 discs (chassis) + (N-1) discs, the first need to move (N-1) a disk to B, and then, the last disk of a is moved to C, and then the B (N-1) disc moved to C.
Write a function, given the input n, a, B, C, to print out the moving steps:
Move (n, a, B, c)
For example, enter move (2, ' A ', ' B ', ' C ') to print out:
A–> B
A–> C
B–> C

Background information:
Hanoi: Hanoi (also known as Hanoi) is a puzzle toy from an ancient Indian legend. When big Brahma created the world, he made three diamond pillars, and stacked 64 gold discs on a pillar from bottom to top in order of size. The great Brahma commanded the Brahman to rearrange the discs from below to the other pillars in order of size. It is also stipulated that the disc cannot be enlarged on the small disc, and only one disc can be moved between the three pillars at a time.

The code is implemented in the following way:

def move (n, a, B, c):    if n==1:        print A, '--', C        return    else:        Move (n-1,a,c,b)  #首先需要把 (N-1) A disc moves to B move         (1,a,b,c)    #将a的最后一个圆盘移动到c Move (        n-1,b,a,c)  #再将b的 (N-1) discs move to Cmove (4, ' A ', ' B ', ' C ')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.