задание 1: функции первых двух пунктов
This commit is contained in:
parent
82e988c965
commit
66c2a4cfda
|
|
@ -0,0 +1,92 @@
|
|||
import csv
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from collections import defaultdict
|
||||
|
||||
# увеличиваем лимит рекурсии
|
||||
sys.setrecursionlimit(25000)
|
||||
|
||||
|
||||
# 1. связный список, узел: {'name': 'Имя', 'phone': '123', 'next': None}
|
||||
|
||||
# проходит до конца и добавляет в конец
|
||||
def ll_insert(head, name, phone):
|
||||
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
|
||||
|
||||
# ищет узел, возвращает телефон или None
|
||||
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']
|
||||
|
||||
current = head
|
||||
while current['next'] is not None:
|
||||
if current['next']['name'] == name:
|
||||
current['next'] = current['next']['next']
|
||||
return head
|
||||
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
|
||||
|
||||
|
||||
# 2. хеш-таблица
|
||||
|
||||
# хеш-функция для вычисления бекета
|
||||
def ht_hash(name, size):
|
||||
return hash(name) % size
|
||||
|
||||
# вычисляет индекс, вызывает ll_insert для соответствующего бакета
|
||||
def ht_insert(buckets, name, phone):
|
||||
size = len(buckets)
|
||||
idx = ht_hash(name, size)
|
||||
buckets[idx] = ll_insert(buckets[idx], name, phone)
|
||||
|
||||
# поиск по хеш-таблице
|
||||
def ht_find(buckets, name):
|
||||
size = len(buckets)
|
||||
idx = ht_hash(name, size)
|
||||
return ll_find(buckets[idx], name)
|
||||
|
||||
# удаление из хеш-таблицы
|
||||
def ht_delete(buckets, name):
|
||||
size = len(buckets)
|
||||
idx = ht_hash(name, size)
|
||||
buckets[idx] = ll_delete(buckets[idx], name)
|
||||
|
||||
# собирает все записи из всех бакетов и сортирует
|
||||
def ht_list_all(buckets):
|
||||
all_records = []
|
||||
for head in buckets:
|
||||
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
|
||||
Loading…
Reference in New Issue
Block a user