So I am trying to do memoization in a python fibonacci(n) function.
def fib(n, memo = [None] * (fibn+1)):
if memo[n] != None: return memo[n]
if n <= 2: return 1
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
I am trying to find a way to store the solutions of values, which I already computed. My temporary solution to that is to make a list memo = [None] * (fibn+1)
and if a new value is computed: memo[n] = fib(n)
. The problem I have with this is that the list is mostly empty and is overall very inefficient. I want to go from this
memo = [None, 1, None, 2, None, None, etc...]
to something like this
memo = {
3: 2
4: 3
7: 13
}
which is just like an object in Java.