From c4a7d2a1bf69bfa17490716189de59c481479a7c Mon Sep 17 00:00:00 2001 From: meosyam Date: Thu, 3 Sep 2026 12:53:35 +0000 Subject: [PATCH] [1] add hash tabel --- meosyam/docs/data/1/phonebook.py | 49 ++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/meosyam/docs/data/1/phonebook.py b/meosyam/docs/data/1/phonebook.py index f362b462..d04fe1bf 100644 --- a/meosyam/docs/data/1/phonebook.py +++ b/meosyam/docs/data/1/phonebook.py @@ -46,14 +46,45 @@ def ll_list_all(head): res.sort(key=lambda x: x[0]) return res +SIZE = 5 + +def hash_func(name): + s = 0 + for ch in name: + s += ord(ch) + return s % SIZE + +def ht_insert(buckets, name, phone): + idx = hash_func(name) + buckets[idx] = ll_insert(buckets[idx], name, phone) + return buckets + +def ht_find(buckets, name): + idx = hash_func(name) + return ll_find(buckets[idx], name) + +def ht_delete(buckets, name): + idx = hash_func(name) + buckets[idx] = ll_delete(buckets[idx], name) + return buckets + +def ht_list_all(buckets): + all_rec = [] + for head in buckets: + cur = head + while cur: + all_rec.append((cur['name'], cur['phone'])) + cur = cur['next'] + all_rec.sort(key=lambda x: x[0]) + return all_rec if __name__ == '__main__': - head = None - head = ll_insert(head, 'Pasha', '123-456') - head = ll_insert(head, 'Andrey', '789-012') - head = ll_insert(head, 'Alisa', '345-678') - head = ll_insert(head, 'Anna', '111-222') - print("All:", ll_list_all(head)) - print("Find Pasha:", ll_find(head, 'Pasha')) - head = ll_delete(head, 'Andrey') - print("After delete Andrey:", ll_list_all(head)) \ No newline at end of file + buckets = [None] * SIZE + ht_insert(buckets, '1', '123-456') + ht_insert(buckets, '2', '789-012') + ht_insert(buckets, '3', '345-678') + ht_insert(buckets, '4', '111-222') + print("HT all:", ht_list_all(buckets)) + print("HT find 1:", ht_find(buckets, '1')) + ht_delete(buckets, '2') + print("HT after delete 2:", ht_list_all(buckets)) \ No newline at end of file