Recursion can help us solve problems when repetitive operations are required and the operating range is regularly changed.
Characteristics of recursion:
1, recursion is to call itself in the function
2, in the use of recursion, must have a clear end condition, to become a recursive export
3, recursive algorithm is usually very concise, but less efficient, so generally do not advocate the use of recursive algorithm design program
4, in the process of recursive invocation, the system for each layer of return points, local variables, such as the opening up a stack to store, too many recursive times to cause stack overflow, etc.
Requirements for using recursion:
1, each time relative to the previous complexity (generally operating range) has been reduced (usually halved)
2, adjacent to two repetitions have a close relationship, the previous time to prepare for the next (usually the previous output as the last input)
3, when the problem complexity is very small, to give the exact answer (recursive end condition), and then no longer recursive call
Look at the following example:
1 defCalc (n):2 Print(n)3 ifN/2 >1:4res = Calc (n/2)5 Print("See when I print and how many times I print:", Res)6 Print("look at the change in the value of N:", N)7 returnN8
9Calc (20)
2010.05.02.51.25 See change in value of N: 1.25 See when I print and print: 1.25 See changes in the value of N: 2.5 see when I print and print: 2.5 See changes in the value of N: 5.0 see when I print and how many times I print: 5.0 See change in value of N: 10.0 See when I print and print: 10.0 See changes in the value of N: 20
According to the above results, we can see the order of recursion execution.
The Fibonacci sequence is implemented using a recursive algorithm:
Fibonacci sequence principle: The sum of a number equal to the first two numbers in a sequence (n>=3)
1>>>2>>>defGet_fbnq (arg1,arg2,stop):3 " "print Fibonacci that cut sequence fragment, capped to stop" "4 ifArg1 = =0:5 Print(ARG1,ARG2)6Arg3 = Arg1 +arg27 ifArg3 <Stop:8 Print(ARG3)9 get_fbnq (arg2,arg3,stop)Ten One A>>> Get_fbnq (0,1,600) -0 1 -1 the2 -3 -5 -8 +13 -21st +34 A55 at89 -144 -233 -377 ->>>
Python-Algorithm Basics-Recursion