Case:
At some point, we want to add a function to multiple functions, such as timing statistics, logging, caching results, etc.
Requirements:
You do not need to add exactly the same code in each function
How to solve?
Pull out the same code and define it as an adorner.
The Fibonacci sequence (the Golden section), starting with the 3rd item of the series, each of which equals the sum of the first two.
For a total of 10 stairs, from the bottom to the top, one can only take a step at a time, and can not retreat, how many methods?
logical arrangement of the above steps :
Each step is a step, the rest is 7~9 a step
If 1 steps are taken, the following 9 steps are required
If 2 steps are taken, the following 8 steps are required
If 3 steps are taken, the following 7 steps are required
This 3 ways to go, by recursion, recursive tree, each recursive generation of child node function
The above two problems through the return of the solution, there will be a problem, there is a repetition of the problem, the process of repetition elimination, in the C + + language called pruning function
#!/usr/bin/python3def Jian_zhi (func): # Intermediate Dictionary, judging if it has been solved median = {} def wrap (*args): # If not in the Middle dictionary, The description is not solved, added to the dictionary, and, in the case, directly returned if args not in median: Median[args] = func (*args) return Median[args] return Wrap@jian_zhidef Fibonacci (N): if n <= 1: return 1 return Fibonacci (n-1) + Fibonacci (n-2) @jian_zhidef Climb (n, steps): count = 0 # When the last step is 0, the description finally just walks once if n = = 0: count = 1 # When the last step is not 0, The instructions need to go at least once. elif n > 0: # Three cases are processed separately Momo for step in steps: count + = Climb (n-step, steps) # return Return the count of each recursive return countif __name__ = = ' __main__ ': print (Climb (1, 2, 3)) Print (Fibonacci (20))
The so-called pruning function is only to guarantee the uniqueness of each recursive function, using the intermediate dictionary to save the functions and parameters that have been executed, by judging the parameters, rejecting the repeated function calls
Python_ pruning function using higher order function