Q8 Memoized Fibonacci

1.问题描述

2.代码

3.总结


一、问题描述:
Description:

The Fibonacci sequence is traditionally used to explain tree recursion.

def fibonacci(n): 
  if n in [0, 1]: 
    return n 
  return fibonacci(n - 1) + fibonacci(n - 2)

This algorithm serves welll its educative purpose but it's tremendously inefficient, not only because of recursion, but because we invoke the fibonacci function twice, and the right branch of recursion (i.e. fibonacci(n-2)) recalculates all the Fibonacci numbers already calculated by the left branch (i.e. fibonacci(n-1)).

This algorithm is so inefficient that the time to calculate any Fibonacci number over 50 is simply too much. You may go for a cup of coffee or go take a nap while you wait for the answer. But if you try it here in Code Wars you will most likely get a code timeout before any answers.

For this particular Kata we want to implement the memoization solution. This will be cool because it will let us keep using the tree recursion algorithm while still keeping it sufficiently optimized to get an answer very rapidly.

The trick of the memoized version is that we will keep a cache data structure (most likely an associative array) where we will store the Fibonacci numbers as we calculate them. When a Fibonacci number is calculated, we first look it up in the cache, if it's not there, we calculate it and put it in the cache, otherwise we returned the cached number.

Refactor the function into a recursive Fibonacci function that using a memoized data structure avoids the deficiencies of tree recursion Can you make it so the memoization cache is private to this function?

二、代码:

** My solution **

fib_dict = {}
def fibonacci(n):
 if n in [0, 1]:
    fib_dict[n] = n
 if n in fib_dict:
    return fib_dict[n]
 else: 
    fib_dict[n] = fibonacci(n - 1) + fibonacci(n - 2) 
    return fib_dict[n]

在问题描述中,已经详细说明了问题解决的思路,因此只需要代码实现就可以了。

** Other Solutions **

  • Best Practices
def memoized(f):
    cache = {}
    def wrapped(k):
        v = cache.get(k)
        if v is None:
            v = cache[k] = f(k)
        return v
    return wrapped

@memoized
def fibonacci(n):
    if n in [0, 1]: 
        return n 
    return fibonacci(n - 1) + fibonacci(n - 2)
  • Clever
def fibonacci(n):
    fib = [0,1] 
    for i in xrange(2,n+1): 
        fib.append(fib[i-1] + fib[i-2]) 
    return fib[n]

你可能感兴趣的:(Q8 Memoized Fibonacci)