2026-rff_mp/KislyuninED/docks/data/1-st-exercize/main.py

84 lines
2.1 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.

# phonebook.py
# Узел списка: {'n': имя, 'p': телефон, 'nxt': следующий}
def ll_insert(head, name, phone):
# обновление, если уже есть
curr = head
while curr is not None:
if curr['n'] == name:
curr['p'] = phone
return head
curr = curr['nxt']
# вставка в начало (новый узел становится головой)
new_node = {'n': name, 'p': phone, 'nxt': head}
return new_node
def ll_find(head, name):
curr = head
while curr is not None:
if curr['n'] == name:
return curr['p']
curr = curr['nxt']
return None
def ll_delete(head, name):
if head is None:
return None
if head['n'] == name:
return head['nxt']
prev = head
curr = head['nxt']
while curr is not None:
if curr['n'] == name:
prev['nxt'] = curr['nxt']
return head
prev = curr
curr = curr['nxt']
return head
def ll_list_all(head):
records = []
curr = head
while curr is not None:
records.append((curr['n'], curr['p']))
curr = curr['nxt']
records.sort(key=lambda x: x[0])
return records
# хеш-функция сумма ord(name) % size
def _hash(name, size):
h = 0
for ch in name:
h += ord(ch)
return h % size
SIZE = 13 # фиксированный размер таблицы
def ht_create():
return [None] * SIZE
def ht_insert(buckets, name, phone):
idx = _hash(name, len(buckets))
buckets[idx] = ll_insert(buckets[idx], name, phone)
return buckets
def ht_find(buckets, name):
idx = _hash(name, len(buckets))
return ll_find(buckets[idx], name)
def ht_delete(buckets, name):
idx = _hash(name, len(buckets))
buckets[idx] = ll_delete(buckets[idx], name)
return buckets
def ht_list_all(buckets):
all_records = []
for head in buckets:
curr = head
while curr:
all_records.append((curr['n'], curr['p']))
curr = curr['nxt']
all_records.sort(key=lambda x: x[0])
return all_records