2026-rff_mp/src/hash_table.py

46 lines
1.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# hash_table.py
# Хеш-таблица с цепочками (использует linked_list.py)
import linked_list as ll
def create_hash_table(size=1000):
"""
Создаёт пустую хеш-таблицу.
size количество корзин (рекомендуется простое число).
"""
return [None] * size
def _hash(name, table_size):
"""Простая хеш-функция на основе суммы кодов символов."""
return sum(ord(ch) for ch in name) % table_size
def ht_insert(table, name, phone):
"""Вставляет или обновляет запись."""
idx = _hash(name, len(table))
# Вставляем в связный список в этой корзине
table[idx] = ll.ll_insert(table[idx], name, phone)
def ht_find(table, name):
"""Ищет телефон по имени."""
idx = _hash(name, len(table))
return ll.ll_find(table[idx], name)
def ht_delete(table, name):
"""Удаляет запись по имени."""
idx = _hash(name, len(table))
table[idx] = ll.ll_delete(table[idx], name)
def ht_list_all(table):
"""
Собирает все записи из всех корзин,
возвращает отсортированный по имени список.
"""
records = []
for bucket in table:
# Каждая корзина голова связного списка
current = bucket
while current is not None:
records.append((current['name'], current['phone']))
current = current['next']
records.sort(key=lambda x: x[0])
return record