title: Fibonacci Function Memoization in Python
body: <p>I'm working on a problem in <a href="https://www.codewars.com/" rel="nofollow noreferrer">codewars</a> that wants you to memoize The Fibonacci sequence. My solution so far has been:</p>
  
  
  
  <pre class="lang-java prettyprint-override"><code>def fibonacci(n):  
      return fibonacci_helper(n, dict())
  
  def fibonacci_helper(n, fib_nums):
      if n in [0, 1]:
          return fib_nums.setdefault(n, n)
  
      fib1 = fib_nums.setdefault(n - 1, fibonacci_helper(n - 1, fib_nums))
      fib2 = fib_nums.setdefault(n - 2, fibonacci_helper(n - 2, fib_nums))
  
      return fib_nums.setdefault(n, fib1 + fib2)
  </code></pre>
  
  <p>It works reasonably well for small values of n, but slows down significantly beyond the 30 mark, which made me wonder — is this solution even memoized? How would I get this type of solution working fast enough for large values of n? </p>