From 242abe433daff2d0430b564cd12d9116d666463c Mon Sep 17 00:00:00 2001 From: IvanBud123 Date: Tue, 3 Mar 2026 22:01:59 +0300 Subject: [PATCH] [1] add hash func find, insert and hash_func --- BudakovIS/docs/LinkedListPhoneBook.py | 73 +++++++++++---------------- 1 file changed, 29 insertions(+), 44 deletions(-) diff --git a/BudakovIS/docs/LinkedListPhoneBook.py b/BudakovIS/docs/LinkedListPhoneBook.py index e3e849f..2e5284f 100644 --- a/BudakovIS/docs/LinkedListPhoneBook.py +++ b/BudakovIS/docs/LinkedListPhoneBook.py @@ -120,55 +120,40 @@ print("====== END ======") -# 2.hash tables - - -SIZE = 1000 +SIZE = 5 buckets = [None] * SIZE -def hash_func(name): - return hash(name) % SIZE + + +def hash_function(name, size): + return hash(name) % size + def ht_insert(buckets, name, phone): - idx = hash_func(name) - buckets[idx] = ll_insert(buckets[idx], name, phone) - return buckets + index = hash_function(name, len(buckets)) + head = buckets[index] + new_head = ll_insert(head, name, phone) + buckets[index] = new_head + +print(f"\n\n\n ====== TEST INSERT HASH ======") +print(buckets) +ht_insert(buckets, "Ivan", "123-456") +print(buckets) +ht_insert(buckets, "Dima", "789-123") +print(buckets) +ht_insert(buckets, "Boris", "456-789") +print(buckets) +print("====== END TEST ======\n\n\n") + def ht_find(buckets, name): - idx = hash_func(name) - return ll_find(buckets[idx], name) + index = hash_function(name, len(buckets)) + head = buckets[index] + return ll_find(head, name) +print("====== TEST FIND HASH FUN ======") +print("find by name Ivan: ",ht_find(buckets, "Ivan")) +print("find by name Dima: ",ht_find(buckets, "Dima")) +print("find by name Boris: ", ht_find(buckets, "Boris")) +print("====== END TEST ======") -def ht_delete(buckets, name): - idx = hash_func(name) - buckets[idx] = ll_delete(buckets[idx], name) - return buckets - -def ht_list_all(buckets): - all_records = [] - for head in buckets: - current = head - while current is not None: - all_records.append((current['name'], current['phone'])) - current = current['next'] - all_records.sort(key=lambda pair: pair[0]) - return all_records - - - -print("---- TESTING BUCKETS ----") - -buckets = ht_insert(buckets, 'Alice', '111-111') -buckets = ht_insert(buckets, 'Bob', '222-222') -buckets = ht_insert(buckets, 'Charlie', '333-333') -buckets = ht_insert(buckets, 'Alice', '999-999') - -print(ht_find(buckets, 'Bob')) - -print(ht_find(buckets, 'David')) - -buckets = ht_delete(buckets, 'Bob') - -print(ht_find(buckets, 'Bob')) - -print(ht_list_all(buckets))