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