Implement the tower method in python

Source: Internet
Author: User
Pandas is an ancient and legendary educational toy in India. The movement of the tower can also be seen as a recursive function. Pandas is an ancient and legendary educational toy in India. The movement of the tower can also be seen as a recursive function.

We can describe the number of columns a, B, c, and moving all disks from a to c as follows:
If a has only one disc, it can be directly moved to c;
If a has N disc, it can be seen that a has 1 disc (chassis) + (N-1) disc, first need to move (N-1) disc to B, then, move the last disc of a to c, and then the (N-1) disc of B to c.
Compile a function and input n, a, B, c to print out the moving steps:
Move (n, a, B, c)
For example, enter move (2, 'A', 'B', 'C') and print the following:
A-> B
A-> C
B-> C

Background information:
Tower of Hanoi (also known as Hanoi) is an ancient and legendary educational toy in India. When I created the world, Da Fan Tian made three diamond pillars, stacked 64 gold disks from bottom to top in order of size. The Great Fan Tian command Brahman re-placed the disc from below in order of size on another pillar. It is also stipulated that the disc cannot be enlarged on a small disc, and only one disc can be moved between the three pillars at a time.

The code is implemented as follows:

Def move (n, a, B, c): if n = 1: print a, '-->', c return else: move (n-1, a, c, B) # First you need to move (N-1) disc to B move (1, a, B, c) # move the last disc of a to c move (n-1, B, a, c) # Move the (N-1) disc of B to cmove (4, 'A', 'B', 'C ')

The above is the details about the implementation of the tower pig method in python. For more information, see other related articles in the first PHP community!

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.