Content Summary:
Recursion is the function itself calls itself until a layer exits after the specified condition is met
Recursive properties:
- Must have a definite end condition
- Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion
- Recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will be reduced by a stack of frames. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.
Show Column 1: Ask for 10! The value.
1 #method One recursive implementation2 #/usr/bin/env python3 #-*-coding:utf-8-*-4 #author:w-d5 defsumn (n):6 ifn<=2:#Recursive End Condition7 returnN8 Else:9 return(n * sumn (n-1))#calling the function itselfTen Print(Sumn (10)) One Results: A3628800 - - method Two: For loop implementation theA=1 - forIinchRange (1,11): -a=a*I - Print(a) + Results: -3628800
Example two: The Fibonacci sequence is generated using recursion (the Fibonacci sequence is the sum of the two numbers in the front to get the next number, followed by the subsequent)
1 #/usr/bin/env python2 #-*-coding:utf-8-*-3 #author:w-d4 defFeola (n1,n2):5n3=n1+N26 ifN1>500:#The end condition is greater than7 return8 Print("{}". Format (N1))#Print Value9Feola (N2,N3)#Self-invocationTenFeola (0,1) One Results: A 0 -1 -1 the2 -3 -5 -8 +13 -21st +34 A55 at89 -144 -233 -377View Code
| Second, anonymous function lambda |
An anonymous function, as the name implies, is a function that does not need to display the definition of a function name, but is syntactically constrained by an expression.
Grammar:
1 Function name =Lambda parameter: code
Display columns:
1 #/usr/bin/env python2 #-*-coding:utf-8-*-3 #author:w-d4f=LambdaX,y:x+y#an anonymous function expression5 Print(f (3,2))#called6 Results:758 9 #change posture, define it in a normal way .Ten defmy_add (x, y): One returnx+y A Print(My_add (3,2))#called - Results: -5
Python Basics 4