Python recursive functions

Source: Internet
Author: User

Recursive functions are simply called self-invocation of functions. Using recursive functions can often make code simple and elegant. Complex problems can be broken down into simple sub-problems. Recursion has unparalleled charm, and from famous computer sayings you can see the wonders of recursion:

 is human,to recurse Divine. The iteration is human and the recursion is God. –l Peter Deutsch

In fact, the above sentence is a bit exaggerated, recursion is not perfect, it also has a fatal weakness, that is inefficient execution, and easy to lead to stack overflow (more than 1000 times).

Let's take a look at the recursion from a wonderful diagram.

We use a simple example to compare the difference between recursion and iteration: to find the factorial of n

Here's how to use iterations:

def Jiecheng (n):    result=1     for inch range (N):        result*= (i+1)    print('factorial of%d'%d ' %(N,result))
Jiecheng (
5) #5的阶乘为120

Here's how to use recursion:

def Jiecheng (n):     if n==1:        return 1    else:        return n * (Jiecheng (n-1))

You can see that using recursion can make your code more concise and elegant, and more mathematically beautiful.

The following is a discussion of recursion through the Fibonacci sequence:

1, through the loop to achieve:

A=0b=1 while B <:    print    (b)= B, a+b

2, the ordinary recursive implementation of the Fibonacci sequence:

1 ls=[]2 for in range:3     ifor i ==1:4         ls.append (1)5     else: 6         Ls.append (ls[i-2]+ls[i-1])7print(ls)  #[1, 1, 2, 3, 5, 8, 13, 21 , the "

3, through the tail recursive way to achieve:

def Fbnq (n,a,b):     if n==0:        return  (b)    Else:        return FBNQ (n-1,b,a+b)print for in range (5)])

These three methods are actually the highest iterative efficiency, and then

Python recursive functions

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.