We want to memorize the results of previous recursive computations so the we can reuse them and save ourselves from having to redo certain recursive computations. (Time vs space tradeoff; we're using more space to save ourselves time)
def fac(N):
if N == 1:
return 1
else:
return N*fac(N-1)
print([2**N for N in range(1, 11)])
print([fac(N) for N in range(1, 11)])
1 2 3 4 5 6 7 8 9
1 1 2 3 5 8 13 21 34
$ fib(N) = fib(N-1) + fib(N-2)$
$ fib(1) = 1$
$ fib(2) = 1$
def fib(N):
if N == 1 or N == 2:
return 1
else:
return fib(N-1) + fib(N-2)
print([fib(N) for N in range(1, 10)])
def fib_slow(N, counter):
counter[0] += 1
if N == 1 or N == 2:
return 1
else:
return fib_slow(N-1, counter) + fib_slow(N-2, counter)
counter = [0]
print(fib_slow(20, counter))
print(counter, "steps")
def fib_fast(N, counter, memory):
"""
memory: dict{N: fib(N)}
"""
counter[0] += 1
if N == 1 or N == 2:
return 1
else:
part1 = 0
if N-1 in memory:
part1 = memory[N-1]
else:
part1 = fib_fast(N-1, counter, memory)
part2 = 0
if N-2 in memory:
part2 = memory[N-2]
else:
part2 = fib_fast(N-2, counter, memory)
res = part1 + part2
memory[N] = res
return res
counter = [0]
print(fib_fast(20, counter, {}))
print(counter, "steps")
def A(m, n, depth=0, memory = {}, do_print = True):
if (m, n) in memory:
return memory[(m, n)]
if m == 0:
res = n+1
if do_print:
print(" "*depth, "A({}, {}) = {}".format(m, n, res))
elif n == 0:
if do_print:
print(" "*depth, "A({}, {}) = A({}, {})".format(m, 0, m-1, 1))
res = A(m-1, 1, depth+1)
if do_print:
print(" "*depth, "A({}, {}) = A({}, {}) = {}".format(m, 0, m-1, 1, res))
else:
if do_print:
print(" "*depth, "A({}, {}) = A({}, A({}, {}))".format(m, n, m-1, m, n-1))
res1 = A(m, n-1, depth+1)
if do_print:
print(" "*depth, "A({}, {}) = A({}, A({}, {})) = A({}, {})".format(m, n, m-1, m, n-1, m-1, res1))
res = A(m-1, res1, depth+1)
if do_print:
print(" "*depth, "A({}, {}) = A({}, {}) = {}".format(m, n, m-1, res1, res))
return res
A(2, 3)
x = (1, 2) # A tuple in python is "immutable" and is not allowed to change
# so we can use it as a key in a dictionary that remembers things