From a3c64db4af83610a69d3da8e79dcd0add8fd75d3 Mon Sep 17 00:00:00 2001 From: anikinvd Date: Fri, 22 May 2026 17:49:33 +0000 Subject: [PATCH] [1] Add hash table --- anikinvd/docs/data/1-st-exercise/phonebook.py | 56 ++++++++++++++----- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/anikinvd/docs/data/1-st-exercise/phonebook.py b/anikinvd/docs/data/1-st-exercise/phonebook.py index fc7f8aa..3296d3f 100644 --- a/anikinvd/docs/data/1-st-exercise/phonebook.py +++ b/anikinvd/docs/data/1-st-exercise/phonebook.py @@ -6,12 +6,9 @@ def llist_insert(head, name, phone): current['phone'] = phone return head current = current['next'] - new_node = {'name': name, 'phone': phone, 'next': None} - if head is None: return new_node - current = head while current['next'] is not None: current = current['next'] @@ -31,10 +28,8 @@ def llist_find(head, name): def llist_delete(head, name): if head is None: return None - if head['name'] == name: return head['next'] - prev = head current = head['next'] while current is not None: @@ -56,12 +51,47 @@ def llist_get_all(head): return entries +BUCKET_SIZE = 1000 + +def ht_create(): + return [None] * BUCKET_SIZE + + +def ht_insert(table, name, phone): + idx = hash(name) % len(table) + table[idx] = llist_insert(table[idx], name, phone) + return table + + +def ht_find(table, name): + idx = hash(name) % len(table) + return llist_find(table[idx], name) + + +def ht_delete(table, name): + idx = hash(name) % len(table) + table[idx] = llist_delete(table[idx], name) + return table + + +def ht_get_all(table): + all_entries = [] + for head in table: + current = head + while current is not None: + all_entries.append((current['name'], current['phone'])) + current = current['next'] + all_entries.sort(key=lambda x: x[0]) + return all_entries + + if __name__ == '__main__': - head = None - head = llist_insert(head, "Alice", "111-222") - head = llist_insert(head, "Bob", "333-444") - head = llist_insert(head, "Alice", "555-666") - print(llist_find(head, "Alice")) - print(llist_find(head, "Charlie")) - head = llist_delete(head, "Bob") - print(llist_get_all(head)) \ No newline at end of file + table = ht_create() + ht_insert(table, "Alice", "111-222") + ht_insert(table, "Bob", "333-444") + ht_insert(table, "Alice", "555-666") + print(ht_find(table, "Alice")) + print(ht_find(table, "Bob")) + print(ht_find(table, "Charlie")) + ht_delete(table, "Bob") + print(ht_get_all(table)) \ No newline at end of file