Fibonacci Series is a very common face test, I believe we have seen, anyway I met two times. Recursion is the easiest way to think about it. But to write a recursive, often the interviewer is not satisfied, will cross-examine. What's the problem with this recursion? Is there any other way? There are more ways than problems, jumping on the road to the Royal Park. Here's a summary. Write the program to the interviewer's heart!
Recursive method
The most serious problem with this recursion is the repetition of the computation, in which the recursive branch of the code can see that the function is called recursively two times, so many functions are actually repeated. Finally, we will solve this problem.
def fib01 (n): if n = = 1 or n = = 2:return n else:return fib01 (n-1) + FIB01 (n-2)
Recursive Method 1
Use a list to store the entire Fibonnci sequence, which is the nth item in the list
def fib02 (n): if n = = 1 or n = = 2:return N Else:arr = [1, 1, 2] i = 3 for I in range (3 , n+1): Arr.append (Arr[i-1] + arr[i-2]) return arr[n]
Recursive Method 2
Declare several historical variables to continuously calculate the values of the series, and Exchange variables
def fib03 (n): if n = = 1 or n = = 2:return N else:x = 1 y = 2 for I in range (3, n+1): fi = x + y x = y y = fi return y
Cache Recursive Intermediate Results
Define a dictionary to store the results of the recursive function in _fib_cache, each time judging whether the function is in the cache, in the direct return, not in, and in the cache
_fib_cache = {}def fib04 (n): if n in _fib_cache:return _fib_cache[n] Else: _fib_cache[n] = N if n < ; = 2 Else fib04 (n-1) + fib04 (n-2) return _fib_cache[n]
With the cache, life is a lot better, but look a little awkward. The solitary _fib_cache, how good it is to get a decorator, which obviously can have an adorner.
function Adorner
Def memo (f): Cache = {} def decorated (*args): If args in Cache:return Cache[args] Else: Cache[args] = f (*args) return Cache[args] return decorated
With this decorator function, we can decorate our recursive function.
@memodef fib01 (n): if n = = 1 or n = = 2:return n else:return fib01 (n-1) + FIB01 (n-2)
This article is from the "Candle Shadow Red" blog, be sure to keep this source http://gccmx.blog.51cto.com/479381/1736742
Python algorithm problem----play Fibonacci series