### Find the nth Fibonacci number

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]
``````
•  1 − ```def fib(n): ``` 2 − ``` memo = {0:1, 1:1} ``` 3 − ``` def recursiveFib(n): ``` 4 − ``` if n not in memo: ``` 5 − ``` memo[n] = recursiveFib(n-1)+recursiveFib(n-2) ``` 6 − ``` return memo[n] ``` 7 − ``` return recursiveFib(n) ``` 1 + ```def fib(n, memo = {0:1, 1:1}): ``` 2 + ``` if n not in memo: ``` 3 + ``` memo[n] = fib(n-1)+fib(n-2) ``` 4 + ``` return memo[n] ``` 8 8 ``` ```

### Find the nth Fibonacci number O(1)

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))``````
•  1 − ```def fib(x): ``` 2 − ``` f1, f2 = 0, 1 ``` 3 − ``` for x in range(x): ``` 4 − ``` f1, f2 = f2, (f1 + f2) ``` 5 − ``` return f2 ``` 1 + ```import math ``` 2 + ```def fib(n): ``` 3 + ``` return long((((1+math.sqrt(5))/2)**(n+1) - ((1-math.sqrt(5))/2)**(n+1))/math.sqrt(5)) ```