fib with memoization
This commit is contained in:
parent
835dfb6314
commit
08a4142b4a
|
@ -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)
|
|
@ -23,6 +23,10 @@ def hash(word):
|
||||||
return hash_key % 16
|
return hash_key % 16
|
||||||
|
|
||||||
|
|
||||||
|
def get_at_hash(key, container):
|
||||||
|
return container[hash(key)]
|
||||||
|
|
||||||
|
|
||||||
def insert_at_hash(key, value, container):
|
def insert_at_hash(key, value, container):
|
||||||
key_hash = hash(key)
|
key_hash = hash(key)
|
||||||
|
|
||||||
|
@ -32,11 +36,11 @@ def insert_at_hash(key, value, container):
|
||||||
return container
|
return container
|
||||||
else:
|
else:
|
||||||
# resolve collision
|
# 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]
|
existing_value = container[key_hash]
|
||||||
|
container[key_hash] = [[existing_value], [key, value]]
|
||||||
|
return container
|
||||||
def get_at_hash(key, container):
|
|
||||||
return container[hash(key)]
|
|
||||||
|
|
||||||
|
|
||||||
container = [None for i in range(15)]
|
container = [None for i in range(15)]
|
||||||
|
@ -45,4 +49,4 @@ insert_at_hash("bad", "evil", container)
|
||||||
insert_at_hash("dab", "good", container)
|
insert_at_hash("dab", "good", container)
|
||||||
|
|
||||||
|
|
||||||
get_at_hash("dab", container)
|
get_at_hash("bad", container)
|
||||||
|
|
Loading…
Reference in New Issue