function recursive thinking in Python, and comparing iterations and recursion to solve Fibonacci sequences

Source: Internet
Author: User

What is recursion? Simply put: The function itself calls itself.

"Ordinary programmers use iterations, genius programmers use recursion"

Although recursive at run time will constantly out stack stack, call the underlying register, resulting in space occupancy and slow time,

But on some algorithms, recursion is still very practical.

However, it is important to note that:

#递归是自己调用自己 is very time consuming and there is a danger of consuming space, so recursive recursion must know "Homeward Bound"

#所谓 "Homeward Bound" means two principles of recursion:
#1. The function itself is called
#2. Set its own correct return value (must have a correct return stop condition, cannot go indefinitely)

Give a simple example

The following is a comparison of the factorial that is implemented with iterations and recursion:

# To implement factorial with a looping function: def factorial (n):      for  in range (1, N):        *= i    return  n# recursive version of the factorial implementation:  def  factorial (n):    if n = =1        :return 1    Else :         return n * Factorial (n-1)

The following is a comparison of the Fibonacci sequences implemented using iterations and recursion:

#recursive implementation of the Fibonacci sequence:  #1. Using an iterative approachdefFibonacci (N): N1= 1N2= 1N3= 2ifN <0:return-1Print('Error,please Enter a correct month ...')    elifn = = 1:        returnN1elifn = = 2:        returnN2Else:         forIinchRange (3,n+1): N3= n2 +N1 N1=n2 N2=N3returnN3#2. Implement it in a recursive waydefFab (n):ifN < 1:        Print('wrong input ...')        return-1elifn = = 1orn = = 2:        return1Else:        returnFab (n-1) + Fab (n-2)    

function recursive thinking in Python, and comparing iterations and recursion to solve Fibonacci sequences

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.