fib with memoization

This commit is contained in:
Emanuel Rodriguez 2023-08-12 00:47:26 -07:00
parent 835dfb6314
commit 08a4142b4a
2 changed files with 37 additions and 5 deletions

28
python/fib.py Normal file
View File

@ -0,0 +1,28 @@
def fib(n, counter):
if n == 0 or n == 1:
return n
else:
counter.append(1)
print("calling fib")
return fib(n - 1, counter) + fib(n - 2, counter)
def fib_memo(n, memo={}, counter=[]):
if n == 0 or n == 1:
return n
if not memo.get(n):
counter.append(1)
memo[n] = fib_memo(n - 1, memo, counter) + fib_memo(n - 2, memo, counter)
return memo[n]
count = []
fib(6, counter=count)
sum(count)
fib_counter = []
fib_memo(6, memo={}, counter=fib_counter)
sum(fib_counter)

View File

@ -23,6 +23,10 @@ def hash(word):
return hash_key % 16
def get_at_hash(key, container):
return container[hash(key)]
def insert_at_hash(key, value, container):
key_hash = hash(key)
@ -32,11 +36,11 @@ def insert_at_hash(key, value, container):
return container
else:
# resolve collision
# but I don't know what was the key, it could any permutation
# of the letters BAD in the example I am working through
existing_value = container[key_hash]
def get_at_hash(key, container):
return container[hash(key)]
container[key_hash] = [[existing_value], [key, value]]
return container
container = [None for i in range(15)]
@ -45,4 +49,4 @@ insert_at_hash("bad", "evil", container)
insert_at_hash("dab", "good", container)
get_at_hash("dab", container)
get_at_hash("bad", container)