hash_table

This commit is contained in:
Pavel 2026-05-03 23:26:35 +03:00
parent 2f7370eb01
commit 5770c59bdf

View File

@ -1,24 +1,29 @@
import linked_list as ll import linked_list as ll
def ht_create(size = 100): def ht_create(size=100):
return[None] * size return [None] * size
def _hash(name, size): def ht_get_hash(buckets, name):
return hash(name) % size return hash(name) % len(buckets)
def ht_insert(buckets, name, phone): def ht_insert(buckets, name, phone):
index = _hash(name, len(buckets)) idx = ht_get_hash(buckets, name)
buckets[index] = ll.ll_insert(buckets[index], name, phone) buckets[idx] = ll.ll_insert(buckets[idx], name, phone)
return buckets
def ht_find(buckets, name): def ht_find(buckets, name):
index = hash(name, len(buckets)) idx = ht_get_hash(buckets, name)
return ll.ll_find(buckets[index], name) return ll.ll_find(buckets[idx], name)
def ht_delete(buckets, name): def ht_delete(buckets, name):
index = _hash(name, len(buckets)) idx = ht_get_hash(buckets, name)
buckets[index] = ll.ll_delete(buckets[index], name) buckets[idx] = ll.ll_delete(buckets[idx], name)
return buckets
def ht_list_all(buckets): def ht_list_all(buckets):
pass all_entries = []
for bucket in buckets:
if bucket:
current = bucket
while current:
all_entries.append((current['name'], current['phone']))
current = current['next']
return sorted(all_entries, key=lambda x: x[0])