From 08a4142b4af0fdafdd03c8dcaaacb00f470292de Mon Sep 17 00:00:00 2001 From: ergz Date: Sat, 12 Aug 2023 00:47:26 -0700 Subject: [PATCH] fib with memoization --- python/fib.py | 28 ++++++++++++++++++++++++++++ python/hash-table.py | 14 +++++++++----- 2 files changed, 37 insertions(+), 5 deletions(-) create mode 100644 python/fib.py diff --git a/python/fib.py b/python/fib.py new file mode 100644 index 0000000..99bce72 --- /dev/null +++ b/python/fib.py @@ -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) diff --git a/python/hash-table.py b/python/hash-table.py index 0ecc31f..ccc6083 100644 --- a/python/hash-table.py +++ b/python/hash-table.py @@ -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)