2026-rff_mp/KuznetsovYuM/docs/data/1-st-exercise/phonebook_structures.py

100 lines
2.5 KiB
Python

def linked_list_add(head, name, phone):
curr = head
while curr is not None:
if curr['name'] == name:
curr['phone'] = phone
return head
curr = curr['next']
new_node = {'name': name, 'phone': phone, 'next': None}
if head is None:
return new_node
curr = head
while curr['next'] is not None:
curr = curr['next']
curr['next'] = new_node
return head
def linked_list_find(head, name):
curr = head
while curr is not None:
if curr['name'] == name:
return curr['phone']
curr = curr['next']
return None
def linked_list_remove(head, name):
if head is None:
return None
if head['name'] == name:
return head['next']
prev = head
curr = head['next']
while curr is not None:
if curr['name'] == name:
prev['next'] = curr['next']
return head
prev = curr
curr = curr['next']
return head
def linked_list_collect_all(head):
records = []
curr = head
while curr is not None:
records.append((curr['name'], curr['phone']))
curr = curr['next']
records.sort(key=lambda pair: pair[0])
return records
def _hash_bucket_index(key, table_size):
return hash(key) % table_size
def hash_table_create(bucket_count=10):
return [None] * bucket_count
def hash_table_put(table, name, phone):
idx = _hash_bucket_index(name, len(table))
table[idx] = linked_list_add(table[idx], name, phone)
return table
def hash_table_get(table, name):
idx = _hash_bucket_index(name, len(table))
return linked_list_find(table[idx], name)
def hash_table_remove(table, name):
idx = _hash_bucket_index(name, len(table))
table[idx] = linked_list_remove(table[idx], name)
return table
def hash_table_collect_all(table):
all_records = []
for head in table:
curr = head
while curr is not None:
all_records.append((curr['name'], curr['phone']))
curr = curr['next']
all_records.sort(key=lambda pair: pair[0])
return all_records
# Quick test
if __name__ == '__main__':
ht = hash_table_create(5)
ht = hash_table_put(ht, 'Alice', '111')
ht = hash_table_put(ht, 'Bob', '222')
ht = hash_table_put(ht, 'Alice', '333')
print(hash_table_get(ht, 'Alice')) # 333
print(hash_table_get(ht, 'Charlie')) # None
ht = hash_table_remove(ht, 'Bob')
print(hash_table_collect_all(ht)) # [('Alice','333')]