Python Recursive Implementation of the tower algorithm example, python Tower

Source: Internet
Author: User

Python Recursive Implementation of the tower algorithm example, python Tower

This example describes how to implement the tower pig algorithm recursively in Python. We will share this with you for your reference. The details are as follows:

For the last interview question, the interviewer asked me to implement the Linglong Algorithm in five minutes (I forgot what Linglong is ).

After painstaking consideration, I came back and checked out the topic and algorithm of qingta. The answer and implementation are as follows:

Base A has 64 plates, which are smaller at the bottom. Each time A plate is moved, the base must be larger at the bottom. All are moved to base B, and base C is the auxiliary base.

#-*-Coding: UTF-8-*-# Recursive Implementation of repeat tower tracing # assume that the initial pole of the parameter is a, the pole of the phase is c, and the end pole of the phase is B # Step 1, a State moves to c # with B, step 2 with a and Step 3 with B #. c moves to bclass Solution with a: def hanoi (self, n, a, B, c ): global lishan if n> 0: Solution. hanoi (self, n-1, a, c, B) B. append (lishan [n-1]). remove (lishan [n-1]) Solution. hanoi (self, n-1, c, B, a) so = Solution () n = 3 global lishanlishan = [x for x in xrange (n)] A = [x for x in xrange (n)] B = [] C = [] so. hanoi (3, A, B, C) print B

Running result:

[2, 1, 0]

Back-to-recursion: it is still very difficult to design (without memorizing this question)

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.