Ad

This is possible because python has mutable default arguments. It is functionally the same as the lrucache approach (though arguably less pythonic)

I like this approach because it allows you to reset the cache when needed, while also keeping it between problems, so if you want to keep looking for fib numbers, the memoization is already done, but if you're using this method for something like kepping track of visited nodes in a graph, you can just clear the cache every time you make a new graph.

Code
Diff
  • def fib(n, memo = {0:1, 1:1}):
        if n not in memo:
            memo[n] = fib(n-1)+fib(n-2)
        return memo[n]
        
    • def fib(n):
    • memo = {0:1, 1:1}
    • def recursiveFib(n):
    • if n not in memo:
    • memo[n] = recursiveFib(n-1)+recursiveFib(n-2)
    • return memo[n]
    • return recursiveFib(n)
    • def fib(n, memo = {0:1, 1:1}):
    • if n not in memo:
    • memo[n] = fib(n-1)+fib(n-2)
    • return memo[n]

Start getting floating point errors around number 70. Darn you Python.

Code
Diff
  • import math
    def fib(n):
        return long((((1+math.sqrt(5))/2)**(n+1) - ((1-math.sqrt(5))/2)**(n+1))/math.sqrt(5))
    • def fib(x):
    • f1, f2 = 0, 1
    • for x in range(x):
    • f1, f2 = f2, (f1 + f2)
    • return f2
    • import math
    • def fib(n):
    • return long((((1+math.sqrt(5))/2)**(n+1) - ((1-math.sqrt(5))/2)**(n+1))/math.sqrt(5))