2026-rff_mp/semyanovra/docs/data/1-st/main.py

101 lines
2.8 KiB
Python

def ll_insert(head, name, phone):
current = head
while current is not None:
if current['name'] == name:
current['phone'] = phone
return head
current = current['next']
new_node = {'name': name, 'phone': phone, 'next': None}
if head is None:
return new_node
current = head
while current['next'] is not None:
current = current['next']
current['next'] = new_node
return head
def ll_find(head, name):
current = head
while current is not None:
if current['name'] == name:
return current['phone']
current = current['next']
return None
def ll_delete(head, name):
if head is None:
return None
if head['name'] == name:
return head['next']
prev = head
current = head['next']
while current is not None:
if current['name'] == name:
prev['next'] = current['next']
return head
prev = current
current = current['next']
return head
def ll_list_all(head):
records = []
current = head
while current is not None:
records.append((current['name'], current['phone']))
current = current['next']
records.sort(key=lambda x: x[0])
return records
HASH_SIZE = 997
def hash_func(name, size):
return hash(name) % size
def ht_create():
return [None] * HASH_SIZE
def ht_insert(table, name, phone):
idx = hash_func(name, len(table))
table[idx] = ll_insert(table[idx], name, phone)
return table
def ht_find(table, name):
idx = hash_func(name, len(table))
return ll_find(table[idx], name)
def ht_delete(table, name):
idx = hash_func(name, len(table))
table[idx] = ll_delete(table[idx], name)
return table
def ht_list_all(table):
all_records = []
for head in table:
current = head
while current is not None:
all_records.append((current['name'], current['phone']))
current = current['next']
all_records.sort(key=lambda x: x[0])
return all_records
if __name__ == "__main__":
print("=== Тестирование связного списка ===")
head = None
head = ll_insert(head, "Ivan", "123-456")
head = ll_insert(head, "Boris", "789-012")
head = ll_insert(head, "Anna", "345-678")
head = ll_insert(head, "Ivan", "111-222")
print("LinkedList:", ll_list_all(head))
print("\n=== Тестирование хеш-таблицы ===")
ht = ht_create()
ht = ht_insert(ht, "Ivan", "123-456")
ht = ht_insert(ht, "Boris", "789-012")
ht = ht_insert(ht, "Anna", "345-678")
ht = ht_insert(ht, "Ivan", "111-222")
print("HashTable entries:", ht_list_all(ht))
print("Find Ivan:", ht_find(ht, "Ivan"))
ht = ht_delete(ht, "Boris")
print("After delete Boris:", ht_list_all(ht))