All checks were successful
Deploy to birb co. production / deploy (push) Successful in 10s
48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
# also called "double hashing"
|
|
|
|
class Dictionary:
|
|
backing: "list" = [None] * 100
|
|
|
|
def hash(self, key: str):
|
|
ord_total = 0;
|
|
for letter in key:
|
|
ord_total += ord(letter)
|
|
return ord_total % len(self.backing)
|
|
|
|
def secondary_hash(self, key: str):
|
|
# never actually use this; this is just a demo
|
|
return len(key) + 1 # ensure never 0
|
|
|
|
def get_actual_index(
|
|
self,
|
|
key: str,
|
|
num_attempts = 0,
|
|
):
|
|
# handles repeated hashing
|
|
index = self.hash(key) + num_attempts * self.secondary_hash(key)
|
|
|
|
# for retrieving a value:
|
|
# if key at index matches key, we have the correct index
|
|
# otherwise, hash again
|
|
if self.backing[index] is not None and self.backing[index][0] != key:
|
|
return self.get_actual_index(key, num_attempts + 1)
|
|
|
|
return index
|
|
|
|
def get(self, key: str):
|
|
index = self.get_actual_index(key)
|
|
return self.backing[index][1]
|
|
|
|
def set(self, key: str, value):
|
|
index = self.get_actual_index(key)
|
|
# instead of storing just values, store tuples (key-value pairs)
|
|
self.backing[index] = (key, value)
|
|
|
|
sample_dict = Dictionary()
|
|
sample_dict.set("test string", "test value")
|
|
sample_dict.set("tets string", "this value will *not* overwrite the other one")
|
|
print(sample_dict.get("test string"))
|
|
print(sample_dict.get("tets string"))
|
|
|
|
print(sample_dict.backing)
|