Python Diary _ Recursion

Source: Internet
Author: User

Recursive algorithm

1. Definition of recursion
Recursion, which is a subroutine (or function) that calls itself directly or indirectly through a series of invocation statements, is a basic way to describe the problem and solve the problem.
Recursive often and divide the thought use simultaneously, can produce many university's algorithm. Recursion is commonly used to solve structural similarity problems. The so-called structure similarity refers to the sub-problems which constitute the original problem are structurally similar to the original problem and can be solved by a similar method. Specifically, the whole problem can be divided into two parts: the first part is some special cases, there is a direct solution; The second part is similar to the original problem, but smaller than the original problem, and depends on the result of the first part. In fact, recursion is one or a few small problems that can be transformed into one or a few minor issues, and then the small problems are further decomposed into smaller ones, until every small problem is solved directly. Therefore, there are two basic elements of recursion:
(1) Boundary condition: Determines when recursion is terminated, also known as a recursive exit.
(2) Recursive mode: Big problem is how to decompose into small problems, also known as recursive body.
Recursive functions only have these two elements in order to obtain the results after finite calculation.
2. Recursive algorithm Example

2.1 Finding the factorial of an integer n
The definition of factorial is as follows:

Based on the recursive definition of factorial, it is very easy to write a recursive algorithm for finding factorial.

def factorial (n):   if n = = 1    :return 1         # recursive end  return n * factorial (n -1)  # problem size minus 1, recursive call

2.2 Connaught Tower
The Hanoi tower problem is a classic application of recursive functions, which comes from an ancient legend: a Diamond Pagoda A, which has 64 Kingdee on the world's first creation. All dishes are stacked from the bottom of the tower to the top of the pagoda in order from large to small. Next to this tower there are two other diamond Pagodas B and C. From the date of the founding of the world, the pastor of Solomon had been trying to move the plates on tower A to C, with the help of Tower B. You can only move one plate at a time, and at no time can you place a dish on a smaller plate than it is. When the priests finished the task, the end of the world was over.
The solution to the Hanoi tower problem can be achieved by the following 3 steps:
(1) the n-1 plate on tower A is moved to Tower B by means of C tower;
(2) Move the remaining plate on tower A to tower C;
(3) Move the n-1 plate from tower A to tower C on the B tower.
Obviously, this is a recursive solution process, assuming that the plate number n=3, the solution of the Hanoi tower problem is as shown:

Hanoi recursive algorithm (Python implementation):

def Hanoi (n, A, B, C):   if (n = = 1): Move    (A, C   )# indicates that only one plate is moved directly from tower A to Tower C  else  :    -1, A, C, B)  # Move the n-1 on the rest of a tower to tower B with the C Tower moving    (A, C)              #  Move the last one on the a directly to Tower C    Hanoi (n-1, B, A, C)  # Move the n-1 plate on Tower B to Tower C with a tower.

 

the running trajectory of the recursive function
With the example of Hanoi, we can explain the running trajectory of recursive function. In the recursive function, both the calling function and the called function are the same function, it is necessary to pay attention to the function call hierarchy, if the call recursive function of the main function is called the No. 0 layer, after entering the function, the first recursive call itself called the 1th layer call, from the level I recursive call itself called the i+1 layer. Conversely, exiting the i+1 layer call should return to layer I. Is the running trajectory of the Hanoi algorithm at n=3, with numbers on the arcs indicating the order of execution of the recursive call and return.

Hanoi's Recursive algorithm code implementation:

#Coding=utf-8I= 1defMove (n, Mfrom, MTO):GlobalIPrint "Step%d: Set%d plate from%s"%(i, N, Mfrom, MTO) I+ = 1defHanoi (N, A, B, C):ifn = = 1: Move (1, A, C)Else: Hanoi (n-1, A, C, B) Move (n, A, c) Hanoi (n-1, B, A, C)#******************** Program Entry **********************Try: N= Int (Raw_input ("Please input a integer:"))  Print "move the steps as follows:"Hanoi (N,'A','B','C')exceptValueError:Print "Please input a integer n (n > 0)!" 

 

Execution Result:

2.3 Fibonacci Sequence
The Fibonacci sequence is such a sequence: 0, 1, 1, 2, 3, 5, 8, 13, 、......。
The core idea of the Fibonacci sequence is:
From the third item, each entry is equal to the sum of the first two items, i.e. f (n) = f (N-1) + f (N-2) (N >= 2)
and stipulates F (0) = 0,f (1) = 1

Requirements: A recursive algorithm is used to obtain the Fibonacci sequence of the specified item.

#!/usr/bin/python#Coding=utf-8deffib_list (n):ifn = = 1orn = = 2 :    return1Else: M= Fib_list (n-1) + fib_list (n-2)    returnmPrint "********** Enter the value of the number of Fibonacci numbers to print by n ***********"Try: N= Int (Raw_input ("Enter:"))exceptValueError:Print "Please enter an integer! "exit () List2=[0]tmp= 1 while(TMP <=N): List2.append (Fib_list (TMP)) TMP+ = 1PrintList2

 

Execution Result:

Python Diary _ Recursion

Related Article

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.