2026-rff_mp/sorokinfi/427.md

4.9 KiB

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

3. двоичное дерево поиска

узел — словарь: {'name': 'Имя', 'phone': '123', 'left': None, 'right': None}

рекурсивно или итеративно вставляет, возвращает новый корень (если корень меняется)

def bst_insert(root, name, phone): if root is None: return {'name': name, 'phone': phone, 'left': None, 'right': None}

if name < root['name']:
    root['left'] = bst_insert(root['left'], name, phone)
elif name > root['name']:
    root['right'] = bst_insert(root['right'], name, phone)
else:
    root['phone'] = phone
return root

поиск

def bst_find(root, name): if root is None: return None if name == root['name']: return root['phone'] elif name < root['name']: return bst_find(root['left'], name) else: return bst_find(root['right'], name)

удаление, возвращает новый корень

def bst_delete(root, name): if root is None: return None

if name < root['name']:
    root['left'] = bst_delete(root['left'], name)
elif name > root['name']:
    root['right'] = bst_delete(root['right'], name)
else:
    # одна ветвь или её отсутствие
    if root['left'] is None:
        return root['right']
    if root['right'] is None:
        return root['left']
    # две ветви
    successor = root['right']
    while successor['left'] is not None:
        successor = successor['left']
        
    root['name'] = successor['name']
    root['phone'] = successor['phone']
    root['right'] = bst_delete(root['right'], successor['name'])
    
return root

центрированный обход (рекурсивно собирает записи в отсортированном порядке)

def bst_list_all(root): records = [] def _inorder(node): if node is not None: _inorder(node['left']) records.append((node['name'], node['phone'])) _inorder(node['right']) _inorder(root) return records