2026-rff_mp/YanyaevAA/[1].py

133 lines
3.5 KiB
Python

def ll_insert(head, name, phone):
current = head
while current:
if current['name'] == name:
current['phone'] = phone
return head
current = current['next']
new_node = {'name': name, 'phone': phone, 'next': None}
new_node['next'] = head
return new_node
def ll_find(head, name):
current = head
while current:
if current['name'] == name:
return current['phone']
current = current['next']
return None
def ll_delete(head, name):
if head['name'] == name:
return head['next']
current = head
while current['next']:
if current['next']['name'] == name:
current['next'] = current['next']['next']
break
current = current['next']
return head
def quick_sort(arr):
if len(arr) <= 1:
return arr
left = []
middle = []
right = []
pivot = arr[len(arr) // 2][0]
for x in arr:
if x[0]<pivot:
left.append(x)
elif x[0]==pivot:
middle.append(x)
else:
right.append(x)
return quick_sort(left) + middle + quick_sort(right)
def ll_list_all(head):
data= []
current = head
while current:
data.append((current['name'], current['phone']))
current = current['next']
return quick_sort(data)
#хэш-таблица
def ht_insert(buckets, name, phone):
id=hash(name)%len(buckets)
buckets[id] = ll_insert(buckets[id], name, phone)
def ht_find(buckets, name):
id= hash(name)%len(buckets)
return ll_find(buckets[id], name)
def ht_delete(buckets, name):
id= hash(name)%len(buckets)
buckets[id] = ll_delete(buckets[id], name)
def ht_list_all(buckets):
data = []
for head in buckets:
current = head
while current:
data.append((current['name'], current['phone']))
current = current['next']
return quick_sort(data)
#Двоичное дерево поиска
def bst_insert(root, name, phone):
if root is None:
return {'name': name, 'phone': phone, 'left': None, 'right': None}
if root['name'] == name:
root['phone'] = phone
elif name<root['name']:
root['left'] = bst_insert(root['left'], name, phone)
else:
root['right'] = bst_insert(root['right'], name, phone)
return root
def bst_find(root, name):
if root is None:
return None
if root['name'] == name:
return root['phone']
elif name<root['name']:
return bst_find(root['left'], name)
else:
return bst_find(root['right'], name)
def minimum(node):
current = node
while current['left'] is True:
current = current['left']
return current
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']
elif root['right'] is None:
return root['left']
min=minimum(root['right'])
root['name']=min['name']
root['phone']=min['phone']
root['right']=bst_delete(root['right'], min['name'])
return root
def bst_list_all(root):
result=[]
if root:
result.extend(bst_list_all(root['left']))
result.append((root['name'], root['phone']))
result.extend(bst_list_all(root['right']))
return result