Compare commits

..

5 Commits

Author SHA1 Message Date
be98a893a1 [2] maze 2026-05-02 06:49:44 +03:00
3438fa1fe9 [1] Structura_data 2026-03-15 19:24:49 +03:00
ad2d65b1cc [1] struct_data 2026-03-15 19:17:37 +03:00
557d45e06e [1] struct dannych 2026-03-15 18:54:31 +03:00
dfdee49e2d Please enter the commit message for your changes. Lines starting
delete 428.txt
2026-03-15 18:43:44 +03:00
129 changed files with 1734 additions and 971 deletions

1
.gitignore vendored
View File

@ -7,7 +7,6 @@ __pycache__/
# C extensions # C extensions
*.so *.so
.DS_Store
# Distribution / packaging # Distribution / packaging
.Python .Python
build/ build/

View File

View File

View File

View File

View File

@ -1,457 +0,0 @@
head = None
#node1 = {'name' : 'Ivan', 'phone' : '123-456', 'next' : None}
#head = node1
#node2 = {'name' : 'Dima', 'phone' : '789-123', 'next' : None}
#node1['next'] = node2
def ll_insert(head, name, phone):
curent = head
while curent is not None:
if curent['name'] == name:
curent['phone'] = phone
return head
curent = curent['next']
n_node = {'name' : name, 'phone' : phone, 'next' : None}
if head is None:
return n_node
curent = head
while curent['next'] is not None:
curent = curent['next']
curent['next'] = n_node
return head
print("====== TESTING ll_insert FUNC ========")
head = ll_insert(head,'Ivan','123-456')
print(head)
head = ll_insert(head, 'Boris', '123-456')
print(head)
head = ll_insert(head, 'Ivan', '321-654')
print(head)
head = ll_insert(head, 'Dima', '345-678')
print(head)
head = ll_insert(head, 'Boris', '111-222')
print(head)
head = ll_insert(head, 'Methody', '221-112')
head = ll_insert(head, 'Kiril', '112-221')
print(f"======= END TEST =======\n\n\n")
def ll_find(head, name):
curent = head
while curent is not None:
if curent['name'] == name:
return curent['phone']
curent = curent['next']
return None
print("====== TESTING ll_find FUNC ======")
print("Ivan`s phone: "+ ll_find(head, 'Ivan'))
print("Dima`s phone: "+ ll_find(head, 'Dima'))
print("Boris phone: "+ ll_find(head, 'Boris'))
print(f"====== END TEST ======\n\n\n")
def ll_delete(head, name):
if head is None:
return None
if head['name'] == name:
return head['next']
prev = head
curent = head['next']
while curent is not None:
if curent['name'] == name:
prev['next'] = curent['next']
return head
prev = curent
curent = curent['next']
return head
print("====== TEST ll_delete FUNC ======")
print("Del of Dima:", ll_delete(head, 'Dima'))
print("====== END TEST ======")
def ll_list_all(head):
records = []
curent = head
while curent is not None:
records.append((curent['name'],curent['phone']))
curent = curent['next']
records.sort(key=lambda pair: pair[0])
return records
print(f"\n\n\n\n")
print("====== TESTING ll_list_all FUNC ======")
print(ll_list_all(head))
print("====== END ======")
#============================== HASH FUNCTIONS =========================
SIZE = 5
buckets = [None] * SIZE
def hash_function(name, size):
return hash(name) % size
def ht_insert(buckets, name, phone):
index = hash_function(name, len(buckets))
head = buckets[index]
new_head = ll_insert(head, name, phone)
buckets[index] = new_head
return buckets
print(f"\n\n\n ====== TEST INSERT HASH ======")
print(buckets)
ht_insert(buckets, "Ivan", "123-456")
print(buckets)
ht_insert(buckets, "Dima", "789-123")
print(buckets)
ht_insert(buckets, "Boris", "456-789")
print(buckets)
print("====== END TEST ======\n\n\n")
def ht_find(buckets, name):
index = hash_function(name, len(buckets))
head = buckets[index]
return ll_find(head, name)
print("====== TEST FIND HASH FUN ======")
print("find by name Ivan: ",ht_find(buckets, "Ivan"))
print("find by name Dima: ",ht_find(buckets, "Dima"))
print("find by name Boris: ", ht_find(buckets, "Boris"))
print("====== END TEST ======\n\n\n")
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
print("====== TEST FUNC LIST ALL ======")
print(ht_list_all(buckets))
print("====== END TEST ======\n\n\n")
def ht_delete(buckets, name):
index = hash_function(name, len(buckets))
head = buckets[index]
new_head = ll_delete(head, name)
buckets[index] = new_head
return buckets
print("====== GLOBAL TEST FOR HASH BASED FUN ======")
buckets = [None] * 10
ht_insert(buckets, "Ivan", "123-456")
print(buckets)
ht_insert(buckets, "Boris", "789-012")
print(buckets)
ht_insert(buckets, "Anna", "345-678")
print(buckets)
ht_insert(buckets, "Ivan", "111-222") # update
print(buckets)
print("Find Ivan`s phone: ",ht_find(buckets, "Ivan")) # 111-222
print("Find Petr`s phone: ",ht_find(buckets, "Petr")) # None
# Удаляем
print("delite Boris from buckets")
ht_delete(buckets, "Boris")
print("search Boris = ",ht_find(buckets, "Boris")) # None
# Все записи
print("list all records: ",ht_list_all(buckets))
print("====== END GLOBAL TEST ======\n\n\n")
# ======================== TREE FUNC ====================
def create_node(name,phone):
return {'name': name, 'phone': phone, 'left': None, 'right': None}
print("====== START TREE FUNC CHAPTER ======\n\n")
print("====== TEST CREATE NODE FUNC ======")
root = create_node('Ivan', '123-456')
print("Create Ivan node: ",root)
print("====== END TEST ====== \n\n\n")
def bst_insert(root, name, phone):
if root is None:
return create_node(name, phone)
if name == root['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
print("====== TEST INSERT FUNC ======")
root = bst_insert(root, 'Dima', '456-789')
print("add Dima: ", root)
root = bst_insert(root, 'Boris', '789-123')
print("add Boris: ", root)
root = bst_insert(root, 'Eva', '321-123')
print("add Eva: ", root)
print("====== END TEST =======\n\n\n")
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)
print("====== START FIND TEST ======")
print("search by Ivan`s phone: ", bst_find(root, 'Ivan'))
print("search by Eva`s phone: ", bst_find(root,'Eva'))
print("====== END TEST ====== \n\n\n")
def find_min(node):
while node['left'] is not None:
node = node['left']
return node
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']
min_node = find_min(root['right'])
root['name'] = min_node['name']
root['phone'] = min_node['phone']
root['right'] = bst_delete(root['right'], min_node['name'])
return root
def bst_list_all(root):
result = []
def inorder(node):
if node is None:
return
inorder(node['left'])
result.append((node['name'], node['phone']))
inorder(node['right'])
inorder(root)
return result
print("====== GLOBAL TEST TREES ======")
root = None
root = bst_insert(root, "Ivan", "123-456")
print("add Ivan: ", root)
root = bst_insert(root, "Boris", "789-012")
print("add Boris: ", root)
root = bst_insert(root, "Anna", "345-678")
print("add Anna: ", root)
root = bst_insert(root, "Ivan", "111-222") # обновление
print("update Ivan: ", root)
print("Find Ivan`s phone: ",bst_find(root, "Ivan")) # 111-222
print("Find Peter`s phone: ",bst_find(root, "Petr")) # None
root = bst_delete(root, "Boris")
print("Del Boris")
print("Find Boris: ",bst_find(root, "Boris")) # None
print("Find ALL: ",bst_list_all(root)) # [('Anna','345-678'), ('Ivan','111-222')]
print("====== END TEST ======")
# ======================== EXPEREMENT CHAPTER ========================
import random
import time
import csv
import sys
sys.setrecursionlimit(20000)
def generate_records(n, seed=42):
random.seed(seed)
records = []
for i in range(1, n+1):
name = f"User_{i:05d}"
phone = f"{random.randint(100,999)}-{random.randint(1000,9999)}"
records.append((name, phone))
return records
def prepare_datasets(base_records):
shuffled = base_records.copy()
random.shuffle(shuffled)
sorted_records = sorted(base_records, key=lambda x: x[0])
return shuffled, sorted_records
def run_experiment(struct_funcs, records, mode_name, repeats=5):
results = []
for rep in range(repeats):
struct = struct_funcs['create']()
# enter all records
start = time.perf_counter()
for name, phone in records:
struct = struct_funcs['insert'](struct, name, phone)
end = time.perf_counter()
insert_time = end - start
# search for 110 records (100 real + 10 None)
existing_names = [name for name, _ in records]
sample_existing = random.sample(existing_names, 100)
nonexistent = [f"None_{i}" for i in range(10)]
search_names = sample_existing + nonexistent
random.shuffle(search_names)
start = time.perf_counter()
for name in search_names:
_ = struct_funcs['find'](struct, name)
end = time.perf_counter()
find_time = end - start
# delete 10 random records
to_delete = random.sample(existing_names, 10)
start = time.perf_counter()
for name in to_delete:
struct = struct_funcs['delete'](struct, name)
end = time.perf_counter()
delete_time = end - start
results.append({
'structure': struct_funcs['name'],
'mode': mode_name,
'repetition': rep+1,
'insert_time': insert_time,
'find_time': find_time,
'delete_time': delete_time
})
return results
def main():
N = 1000
base_records = generate_records(N)
shuffled, sorted_records = prepare_datasets(base_records)
structures = {
'LinkedList': {
'name': 'LinkedList',
'create': lambda: None,
'insert': ll_insert,
'find': ll_find,
'delete': ll_delete,
'list_all': ll_list_all
},
'HashTable': {
'name': 'HashTable',
'create': lambda: [None] * 10,
'insert': ht_insert,
'find': ht_find,
'delete': ht_delete,
'list_all': ht_list_all
},
'BST': {
'name': 'BST',
'create': lambda: None,
'insert': bst_insert,
'find': bst_find,
'delete': bst_delete,
'list_all': bst_list_all
}
}
all_results = []
repeats = 5
for struct_name, funcs in structures.items():
print(f"Testing {struct_name} on random order...")
res = run_experiment(funcs, shuffled, 'random', repeats)
all_results.extend(res)
print(f"Testing {struct_name} in sorted order...")
res = run_experiment(funcs, sorted_records, 'sorted', repeats)
all_results.extend(res)
with open('experiment_results.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Structure', 'Mode', 'Repeat', 'Insert (sec)', 'Search (sec)', 'Delete (sec)'])
for r in all_results:
writer.writerow([
r['structure'],
r['mode'],
r['repetition'],
f"{r['insert_time']:.6f}",
f"{r['find_time']:.6f}",
f"{r['delete_time']:.6f}"
])
print("The experiment is complete. The results are saved in experiment_results.csv.")
if __name__ == '__main__':
main()

View File

@ -1,31 +0,0 @@
Structure,Mode,Repeat,Insert (sec),Search (sec),Delete (sec)
LinkedList,random,1,0.140358,0.007040,0.000844
LinkedList,random,2,0.138009,0.009197,0.000413
LinkedList,random,3,0.114717,0.009266,0.000744
LinkedList,random,4,0.117224,0.006914,0.000531
LinkedList,random,5,0.136302,0.010432,0.000582
LinkedList,sorted,1,0.106921,0.007845,0.000566
LinkedList,sorted,2,0.116404,0.015005,0.004900
LinkedList,sorted,3,0.125122,0.006956,0.000708
LinkedList,sorted,4,0.122401,0.004220,0.000474
LinkedList,sorted,5,0.111422,0.008343,0.000551
HashTable,random,1,0.025442,0.004652,0.000078
HashTable,random,2,0.035477,0.000985,0.000091
HashTable,random,3,0.015387,0.001249,0.000298
HashTable,random,4,0.014196,0.001167,0.000096
HashTable,random,5,0.013819,0.000910,0.000094
HashTable,sorted,1,0.013713,0.000897,0.000060
HashTable,sorted,2,0.016816,0.001013,0.000116
HashTable,sorted,3,0.018408,0.001019,0.000084
HashTable,sorted,4,0.014490,0.000886,0.000093
HashTable,sorted,5,0.012493,0.000867,0.000075
BST,random,1,0.006755,0.000468,0.000065
BST,random,2,0.006454,0.000380,0.000052
BST,random,3,0.003348,0.000266,0.000033
BST,random,4,0.004785,0.000379,0.000053
BST,random,5,0.005253,0.000438,0.000083
BST,sorted,1,0.331066,0.028260,0.002915
BST,sorted,2,0.342009,0.025769,0.003155
BST,sorted,3,0.282425,0.031293,0.002984
BST,sorted,4,0.313816,0.022712,0.002957
BST,sorted,5,0.287008,0.032645,0.002415
1 Structure Mode Repeat Insert (sec) Search (sec) Delete (sec)
2 LinkedList random 1 0.140358 0.007040 0.000844
3 LinkedList random 2 0.138009 0.009197 0.000413
4 LinkedList random 3 0.114717 0.009266 0.000744
5 LinkedList random 4 0.117224 0.006914 0.000531
6 LinkedList random 5 0.136302 0.010432 0.000582
7 LinkedList sorted 1 0.106921 0.007845 0.000566
8 LinkedList sorted 2 0.116404 0.015005 0.004900
9 LinkedList sorted 3 0.125122 0.006956 0.000708
10 LinkedList sorted 4 0.122401 0.004220 0.000474
11 LinkedList sorted 5 0.111422 0.008343 0.000551
12 HashTable random 1 0.025442 0.004652 0.000078
13 HashTable random 2 0.035477 0.000985 0.000091
14 HashTable random 3 0.015387 0.001249 0.000298
15 HashTable random 4 0.014196 0.001167 0.000096
16 HashTable random 5 0.013819 0.000910 0.000094
17 HashTable sorted 1 0.013713 0.000897 0.000060
18 HashTable sorted 2 0.016816 0.001013 0.000116
19 HashTable sorted 3 0.018408 0.001019 0.000084
20 HashTable sorted 4 0.014490 0.000886 0.000093
21 HashTable sorted 5 0.012493 0.000867 0.000075
22 BST random 1 0.006755 0.000468 0.000065
23 BST random 2 0.006454 0.000380 0.000052
24 BST random 3 0.003348 0.000266 0.000033
25 BST random 4 0.004785 0.000379 0.000053
26 BST random 5 0.005253 0.000438 0.000083
27 BST sorted 1 0.331066 0.028260 0.002915
28 BST sorted 2 0.342009 0.025769 0.003155
29 BST sorted 3 0.282425 0.031293 0.002984
30 BST sorted 4 0.313816 0.022712 0.002957
31 BST sorted 5 0.287008 0.032645 0.002415

View File

@ -1,44 +0,0 @@
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Загрузка данных
df = pd.read_csv('experiment_results.csv')
# Усреднение по повторам
mean_times = df.groupby(['Structure', 'Mode'])[['Insert (sec)', 'Search (sec)', 'Delete (sec)']].mean().reset_index()
# Подготовка данных для графиков
structures = mean_times['Structure'].unique()
modes = mean_times['Mode'].unique()
# Создание трех графиков (вставка, поиск, удаление)
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
operations = ['Insert (sec)', 'Search (sec)', 'Delete (sec)']
titles = ['Вставка', 'Поиск', 'Удаление']
for ax, op, title in zip(axes, operations, titles):
# Для каждой структуры строим две колонки (random, sorted)
x = np.arange(len(structures))
width = 0.35
random_vals = []
sorted_vals = []
for s in structures:
random_row = mean_times[(mean_times['Structure']==s) & (mean_times['Mode']=='random')]
sorted_row = mean_times[(mean_times['Structure']==s) & (mean_times['Mode']=='sorted')]
random_vals.append(random_row[op].values[0] if not random_row.empty else 0)
sorted_vals.append(sorted_row[op].values[0] if not sorted_row.empty else 0)
ax.bar(x - width/2, random_vals, width, label='Случайный')
ax.bar(x + width/2, sorted_vals, width, label='Отсортированный')
ax.set_xticks(x)
ax.set_xticklabels(structures)
ax.set_ylabel('Время (сек)')
ax.set_title(title)
ax.legend()
plt.tight_layout()
plt.savefig('../../performance_comparison.png', dpi=150)
plt.show()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

View File

@ -1,60 +0,0 @@
# Отчёт по лабораторной работе "Структуры данных"
## 1. Введение
В рамках работы были реализованы три структуры данных для хранения телефонного справочника: связный список, хеш-таблица и двоичное дерево поиска. Проведено экспериментальное сравнение производительности операций вставки, поиска и удаления на наборе из **10000 записей**. Для каждой структуры тестирование выполнялось на двух вариантах входных данных: случайный порядок и отсортированный по имени. Каждый эксперимент повторялся 5 раз, результаты усреднены.
## 2. Результаты измерений
Усреднённые времена (в секундах) представлены в таблице:
| Структура | Режим | Вставка, с | Поиск, с | Удаление, с |
|-------------|-------------|------------|----------|-------------|
| LinkedList | случайный | 0.1143 | 0.0078 | 0.00065 |
| LinkedList | сортир. | 0.1124 | 0.0068 | 0.00065 |
| HashTable | случайный | 0.0131 | 0.00109 | 0.000085 |
| HashTable | сортир. | 0.0156 | 0.00110 | 0.00014 |
| BST | случайный | 0.00532 | 0.000365 | 0.000053 |
| BST | сортир. | 0.303 | 0.0230 | 0.00268 |
Графическое представление результатов приведено на рисунке ниже.
![Сравнение производительности](performance_comparison.png)
## 3. Анализ результатов
### 3.1. Влияние порядка данных на BST
При вставке элементов в отсортированном порядке двоичное дерево поиска вырождается в линейный список все новые узлы добавляются только в правое поддерево. Высота дерева становится равной количеству элементов, и сложность всех операций возрастает до **O(n)**. Эксперимент подтверждает это:
- Вставка в BST на отсортированных данных заняла **0.303 с**, что в **57 раз** больше, чем на случайных (0.00532 с).
- Время вставки на отсортированных данных даже превышает показатели связного списка (0.112 с), что объясняется дополнительными накладными расходами на рекурсивные вызовы.
- Поиск и удаление также замедлились примерно в 60 раз по сравнению со случайным режимом.
### 3.2. Устойчивость хеш-таблицы к порядку
Хеш-таблица использует хеш-функцию, которая равномерно распределяет ключи по корзинам независимо от порядка поступления. Поэтому производительность операций практически не зависит от того, в каком порядке приходят данные:
- В случайном и отсортированном режимах времена вставки (0.0131 и 0.0156 с) и поиска (около 0.0011 с) близки.
- Небольшие колебания могут быть вызваны случайным распределением коллизий.
- Это соответствует ожидаемой средней сложности **O(1)**.
### 3.3. Медлительность связного списка при поиске
Связный список не обеспечивает прямого доступа к элементам для поиска необходимо просматривать узлы последовательно, что даёт сложность **O(n)**. В эксперименте:
- Время поиска в списке (~0.007 с) на порядок больше, чем в хеш-таблице (0.0011 с) и BST на случайных данных (0.00037 с).
- При увеличении объёма данных эта разница будет только расти.
- Вставка в список также относительно медленна (0.11 с), так как требует прохода до конца (хотя обновление существующего имени выполняется быстрее, но в тесте все имена уникальны, поэтому каждая вставка проходит весь список).
### 3.4. Сравнение удаления
- **Связный список**: удаление требует сначала найти элемент (O(n)), затем переставить ссылки (O(1)). Время удаления (0.00065 с) близко ко времени поиска, что логично.
- **Хеш-таблица**: удаление выполняется за O(1) в среднем сначала определяется корзина, затем из короткого списка удаляется элемент. Время удаления (0.0000850.00014 с) значительно меньше, чем в списке.
- **BST**: на случайных данных удаление очень быстрое (0.000053 с) благодаря логарифмической высоте. На отсортированных данных время возрастает до 0.00268 с (в 50 раз), что отражает деградацию до O(n).
## 4. Выводы и рекомендации по выбору структуры
На основе полученных результатов можно сформулировать следующие рекомендации:
- **Хеш-таблица** оптимальный выбор, если требуется максимальная скорость поиска, вставки и удаления, а порядок хранения не важен. Примеры: реализация словарей, кэшей, индексов по ключу. В эксперименте хеш-таблица показала стабильно высокую производительность во всех режимах.
- **Двоичное дерево поиска** следует применять, когда необходимо получать данные в отсортированном порядке (например, вывод телефонного справочника по алфавиту). Однако важно учитывать, что при поступлении отсортированных данных дерево вырождается, и производительность резко падает. В таких случаях лучше использовать сбалансированные деревья (AVL, красно-чёрные). В эксперименте BST на случайных данных показал отличные результаты, близкие к хеш-таблице, а на отсортированных стал самым медленным.
- **Связный список** практически непригоден для больших объёмов данных из-за линейной сложности основных операций. Может использоваться лишь для очень маленьких коллекций, при частых вставках в начало списка (здесь не рассматривалось) или в учебных целях.
Таким образом, для реальных задач чаще всего выбирают хеш-таблицы или сбалансированные деревья в зависимости от требований к упорядоченности данных.
I use arch BTW

View File

View File

@ -1 +0,0 @@
hi

View File

View File

View File

View File

View File

View File

@ -1 +0,0 @@

View File

View File

View File

@ -1 +0,0 @@
428

View File

View File

View File

@ -1 +0,0 @@
428b

View File

View File

View File

@ -1 +0,0 @@
427.txt

View File

@ -1 +0,0 @@
427.txt

View File

View File

View File

@ -1 +0,0 @@

Binary file not shown.

Binary file not shown.

336
README.md
View File

@ -16,7 +16,7 @@
### Крайний срок приема работ 25.05.2026 до 14:00 ### Крайний срок приема работ 25.05.2026 до 14:00
## Задание 0 -- репозиторий [отдельный срок на создание PR с папкой: 28.02.2026] ## Задание 1 -- репозиторий
0. Создай пользователя (логин — фамилия+инициалы слитно транслитом, как в терминал-классе). 0. Создай пользователя (логин — фамилия+инициалы слитно транслитом, как в терминал-классе).
@ -38,345 +38,17 @@
5. **Сохрани изменения:** 5. **Сохрани изменения:**
```bash ```bash
git add -A git add -A
git commit -m "[0] initial commit" git commit -m "Добавлен файл группы [номер] для [Фамилия]"
``` ```
6. Отправь ветку **в свой форк** на Gitea: 6. Отправь ветку **в свой форк** на Gitea:
```bash ```bash
git push origin git push origin IvanovII
``` ```
если просит, перед этим сделать git push --set-upstream origin
7. **Создай запрос на слияние (Pull Request):** На Gitea перейди в свой форк, выбери ветку `IvanovII`, нажмите **Запрос на слияние**. Убедитесь, что: 7. **Создай запрос на слияние (Pull Request):** На Gitea перейди в свой форк, выбери ветку `IvanovII`, нажмите **Запрос на слияние**. Убедитесь, что:
- Базовый репозиторий: **учебный** (преподавателя) - Базовый репозиторий: **учебный** (преподавателя)
- Базовая ветка: **develop** - Базовая ветка: **develop**
- Сравниваемая ветка: **свой форк / IvanovII** - Сравниваемая ветка: **свой форк / IvanovII**
8. Отправь PR. 8. Отправь PR.
## Задание 1 -- структуры данных
***Напоминание: под каждое задание вы создаете отдельную ветку***
>Для оформления результатов заведи папку **docs** в своей папке и сохраняй туда отчет (в любом формате от .doc до .md, а то и .jpnb). Вспомогательные файлы клади в подпапку **data** внутри **docs**
**Цель работы**
Реализовать три различные структуры данных «с нуля», применить их для хранения записей телефонного справочника и экспериментально сравнить производительность основных операций. Вы должны собственными руками написать код, чтобы понять внутреннее устройство связного списка, хеш-таблицы и двоичного дерева поиска, а также осознать их сильные и слабые стороны на практике.
**!! Задание выполнять в структурной (процедурной) парадигме, не используя классы. Главное реализовать структуры данных «руками» и сравнить их производительность.**
### Базовые операции (обязательны для всех):
`insert(name, phone)` -- добавить или обновить запись.
`find(name)` -- phone или None.
`delete(name)` -- удалить запись, игнорировать отсутствие.
`list_all()` -- список всех записей, отсортированный по имени (для BST inorder обход; для списка и хеш‑таблицы — собрать и отсортировать явно).
#### 1. Связный список (LinkedListPhoneBook)
Узел представляется словарём: `{'name': 'Имя', 'phone': '123', 'next': None}.`
**Функции:**
`def ll_insert(head, name, phone)` — проходит до конца (или сразу добавляет в конец) и возвращает новую голову (если вставка в начало) или изменяет список по ссылке. Удобнее возвращать новую голову, если вставка может быть в начало.
`def ll_find(head, name)` — ищет узел, возвращает телефон или None.
`def ll_delete(head, name)` — удаляет узел, возвращает новую голову.
`def ll_list_all(head)` — собирает все записи в список и сортирует (сортировка вынесена отдельно).
#### 2. Хеш-таблица
Хранится как список buckets фиксированной длины, каждый элемент — голова связного списка (или None).
**Функции:**
`def ht_insert(buckets, name, phone)` — вычисляет индекс, вызывает ll_insert для соответствующего бакета.
Аналогично `ht_find, ht_delete, ht_list_all` (последняя собирает все записи из всех бакетов и сортирует).
#### 3. Двоичное дерево поиска
Узел — словарь: `{'name': 'Имя', 'phone': '123', 'left': None, 'right': None}.`
**Функции:**
`def bst_insert(root, name, phone)` — рекурсивно или итеративно вставляет, возвращает новый корень (если корень меняется).
`def bst_find(root, name)` — поиск.
`def bst_delete(root, name)` — удаление, возвращает новый корень.
`def bst_list_all(root)` — центрированный обход (рекурсивно собирает записи в отсортированном порядке).
### Экспериментальная часть (подробно об измерении времени)
#### 1. Генерация тестовых данных
Создайте список records из N элементов (например, N = 10000). Каждый элемент — кортеж (name, phone).
Имена генерируйте как `f"User_{i:05d}"` (равномерное распределение) или случайные слова из небольшого набора (чтобы были повторения и коллизии). Для проверки влияния порядка подготовьте два варианта одного и того же набора:
`records_shuffled` — случайный порядок.
`records_sorted` — отсортированный по имени (по алфавиту).
#### 2. Инструменты замера времени
Используйте модуль **time**:
```python
import time
start = time.perf_counter()
# ... операции ...
end = time.perf_counter()
elapsed = end - start # время в секундах
```
Для многократных замеров удобен `timeit`, но в этой задаче достаточно просто обернуть код в цикл и усреднить.
#### 3. Проведение замеров
Для каждой структуры данных и для каждого режима входных данных (случайный / отсортированный) выполните:
- А. Вставка всех записей
Создайте пустую структуру.
Засеките время, выполните insert для каждой записи из входного списка.
Зафиксируйте общее время вставки.
- Б. Поиск 100 случайных записей
Возьмите 100 случайных имён из того же набора (гарантированно существующих) и 10 имён, которых нет (например, "None_{i}").
Засеките время на выполнение всех 110 вызовов find.
- В. Удаление 50 случайных записей
Выберите 50 случайных имён из набора.
Засеките время на выполнение delete для каждого.
**!! Важно: после вставки структура остаётся заполненной, поиск и удаление выполняются на ней же. Если нужно повторить замер для другого порядка данных — создавайте новую структуру и заполняйте заново.**
#### 4. Сохранение результатов
**!! Каждый эксперимент повторить минимум 5 раз и записывать и среднее время, и все замеры.**
Соберите все замеры в словарь или список, затем сохраните в CSV-файл:
```python
import csv
results = [
["Структура", "Режим", "Операция", "Время (сек)"],
["LinkedList", "случайный", "вставка", 0.123],
...
]
with open("results.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(results)
```
#### 5. Анализ результатов
Постройте график (столбчатая диаграмма или линейный график) — можно в Excel, Google Sheets или с помощью matplotlib в Python.
Сравните:
- Как порядок входных данных влияет на скорость вставки в BST (деградация до O(n) на отсортированных данных).
- Почему хеш-таблица почти не чувствительна к порядку.
- Почему связный список всегда медленен при поиске.
- Как удаление работает в каждой структуре.
* Вывод должен содержать ответ на вопрос: какую структуру и для каких задач (частые вставки, частый поиск, необходимость получать данные в порядке) стоит выбирать в реальной жизни.*
## Задание: Поиск выхода из лабиринта (объектно-ориентированная реализация с паттернами)
### Цель работы
Разработать гибкую, расширяемую программу для загрузки лабиринта из файла, поиска пути от старта до выхода с возможностью выбора алгоритма, визуализации процесса и экспериментального сравнения алгоритмов. В ходе работы необходимо применить минимум 3 паттерна проектирования из списка GoF, обосновать их выбор и продемонстрировать преимущества такой архитектуры.
### Общая схема приложения (пример)
```mermaid
classDiagram
class Maze {
-Cell[] cells
-int width, height
-Cell start
-Cell exit
+getCell(x,y): Cell
+getNeighbors(cell): List~Cell~
}
class Cell {
-int x, y
-bool isWall
-bool isStart
-bool isExit
+isPassable(): bool
}
class MazeBuilder {
<<interface>>
+buildFromFile(filename): Maze
}
class TextFileMazeBuilder {
+buildFromFile(filename): Maze
}
class PathFindingStrategy {
<<interface>>
+findPath(maze, start, exit): List~Cell~
}
class BFSStrategy
class DFSStrategy
class AStarStrategy
class DijkstraStrategy
class SearchStats {
+timeMs: float
+visitedCells: int
+pathLength: int
}
class MazeSolver {
-Maze maze
-PathFindingStrategy strategy
+setStrategy(strategy)
+solve(): SearchStats
}
class Command {
<<interface>>
+execute()
+undo()
}
class MoveCommand {
-Player player
-Direction dir
-Cell previousCell
+execute()
+undo()
}
class Player {
-Cell currentCell
+moveTo(cell)
}
class Observer {
<<interface>>
+update(event)
}
class ConsoleView {
+update(event)
+render(maze, player, path)
}
MazeBuilder <|.. TextFileMazeBuilder
MazeBuilder --> Maze : creates
PathFindingStrategy <|.. BFSStrategy
PathFindingStrategy <|.. DFSStrategy
PathFindingStrategy <|.. AStarStrategy
PathFindingStrategy <|.. DijkstraStrategy
MazeSolver --> PathFindingStrategy : uses
MazeSolver --> Maze : uses
Command <|.. MoveCommand
MoveCommand --> Player
Player --> Cell
Observer <|.. ConsoleView
MazeSolver --> Observer : notifies
```
### Выполнение
#### Этап 1. Модель лабиринта (без паттернов, просто классы)
**Задача:** Создать классы `Cell` и `Maze`, которые представляют карту лабиринта.
- `Cell` хранит координаты (x, y), флаги `isWall`, `isStart`, `isExit`, метод `isPassable()` (возвращает `True` для прохода, если не стена).
- `Maze` хранит двумерный массив клеток, ширину, высоту, ссылки на стартовую и выходную клетку. Методы: `getCell(x, y)`, `getNeighbors(cell)` возвращает список соседних проходимых клеток (вверх, вниз, влево, вправо, если в пределах границ и не стена).
**Результат:** Лабиринт можно создать вручную в коде, но загрузку пока не делаем.
#### Этап 2. Загрузка лабиринта из файла применение паттерна **Builder**
**Задача:** Реализовать загрузку лабиринта из текстового файла, где `#` стена, ` ` (пробел) проход, `S` старт, `E` выход.
- Создать интерфейс `MazeBuilder` с методом `buildFromFile(filename)`.
- Реализовать класс `TextFileMazeBuilder`, который читает файл, парсит символы, создаёт объекты `Cell`, задаёт координаты и флаги, после чего возвращает готовый `Maze`.
Процесс построения лабиринта сложный (парсинг, валидация, установка старта/выхода). Builder скрывает детали создания от клиента. В будущем можно легко добавить другой формат (например, JSON или бинарный) через новую реализацию `MazeBuilder`.
#### Этап 3. Стратегии поиска пути паттерн **Strategy**
**Задача:** Реализовать семейство алгоритмов поиска пути от старта до выхода.
- Создать интерфейс `PathFindingStrategy` с методом `findPath(maze, start, exit)`, возвращающим список клеток пути (от старта до выхода включительно) или пустой список, если пути нет.
- Реализовать минимум 3 стратегии:
- **BFS** (поиск в ширину) гарантирует кратчайший путь по количеству шагов.
- **DFS** (поиск в глубину) быстрый, но не обязательно кратчайший.
- **A*** (с эвристикой, например, манхэттенское расстояние) компромисс между скоростью и оптимальностью.
- (Опционально) **Дейкстра** полезна для взвешенных лабиринтов, но в базовом варианте все шаги имеют вес 1, тогда она совпадает с BFS.
Каждая стратегия возвращает путь. Для BFS/DFS используйте очередь/стек, для A* приоритетную очередь (heapq). Важно: алгоритмы не должны модифицировать сам лабиринт, только читать состояние клеток.
Strategy позволяет легко переключать алгоритмы во время выполнения, не меняя код остальной программы. Новый алгоритм можно добавить, реализовав интерфейс.
#### Этап 4. Класс-оркестратор **MazeSolver** (использует Strategy)
**Задача:** Создать класс, который принимает лабиринт и стратегию, выполняет поиск и собирает статистику.
- `MazeSolver` содержит поля `maze` и `strategy`.
- Метод `setStrategy(strategy)` для динамической смены алгоритма.
- Метод `solve()` вызывает `strategy.findPath(...)` и возвращает объект `SearchStats` (время выполнения в миллисекундах, количество посещённых клеток, длина найденного пути).
- Для замера времени используйте `time.perf_counter()` до и после вызова стратегии.
#### Этап 5. Визуализация и пошаговое управление паттерны **Observer** и **Command** (по желанию)
**5.1. Наблюдатель (Observer)** обновление консольного интерфейса.
- Создать интерфейс `Observer` с методом `update(event)`, где `event` может быть строкой или объектом с типом события (`"path_found"`, `"move"`, `"maze_loaded"`).
- Реализовать класс `ConsoleView`, который отображает лабиринт, текущее положение игрока (если реализован пошаговый режим) и найденный путь. Метод `render(maze, player_position, path)` рисует карту в консоли.
- `MazeSolver` (или отдельный контроллер) может иметь список наблюдателей и уведомлять их при изменении состояния.
**5.2. Команда (Command)** для пошагового перемещения игрока по найденному пути (или ручного управления).
- Создать интерфейс `Command` с методами `execute()` и `undo()`.
- Реализовать `MoveCommand`, который принимает игрока (`Player`), направление и изменяет его позицию, сохраняя предыдущую для отмены.
- Создать класс `Player`, хранящий текущую клетку.
- Консольное меню позволяет вводить команды (W/A/S/D), выполнять `MoveCommand`, при необходимости отменять последний ход (Ctrl+Z). Это опционально, но очень наглядно демонстрирует паттерн.
*Observer можно реализовать только для вывода сообщений о начале/конце поиска, а Command для демонстрации undo при ручном исследовании лабиринта.*
#### Этап 6. Экспериментальная часть (аналогично заданию со структурами данных)
**Задача:** Сравнить эффективность реализованных стратегий на лабиринтах разной сложности.
1. **Подготовка тестовых лабиринтов:**
- Маленький (10×10) с простым путём.
- Средний (50×50) с тупиками.
- Большой (100×100) с запутанной структурой.
- «Пустой» лабиринт (без стен) для демонстрации максимальной производительности.
- «Без выхода» чтобы проверить обработку отсутствия пути.
2. **Замеры:**
- Для каждого лабиринта и каждой стратегии запустить `solve()` 510 раз, усреднить время, количество посещённых клеток, длину пути.
- Записать результаты в CSV: `лабиринт,стратегия,время_мс,посещено_клеток,длина_пути`.
3. **Анализ:**
- Построить графики для каждого лабиринта.
- Проанализировать и написать выводы по итогам (эффективность того или иного алгоритма в разных случаях).
4. **Дополнительное задание:** Реализовать взвешенные клетки (например, болото вес 3, песок вес 2, асфальт вес 1) и сравнить Дейкстру с A* на взвешенном графе.
#### Этап 7. Отчёт
**Структура отчёта:**
1. Описание задачи и выбранных паттернов (с диаграммой классов из Mermaid).
2. Листинги ключевых классов (можно выборочно) или ссылка на репозиторий.
3. Результаты экспериментов (таблицы, графики).
4. Анализ эффективности алгоритмов и применимости паттернов.
5. Выводы: как ООП и паттерны помогли сделать код гибким и расширяемым. Что было бы сложно изменить без них.
### Советы
- Для A* самая простая эвристика: `abs(x1 - x2) + abs(y1 - y2)`.
- При поиске пути надо хранить предшественников (`parent` для каждой посещённой клетки), чтобы восстановить путь.
- Для BFS/DFS используй `deque` (очередь) и `list` (стек).
- Визуализацию в консоли можно сделать с помощью `os.system('cls' if os.name == 'nt' else 'clear')` для перерисовки.

View File

View File

View File

View File

@ -0,0 +1,50 @@
['Structura', 'shuffled/sorted', 'Operation', 'Time']
LinkedList | shuffled | insert | 3.798362
LinkedList | shuffled | find | 0.028610
LinkedList | shuffled | delete | 0.035444
LinkedList | sorted | insert | 3.117239
LinkedList | sorted | find | 0.020465
LinkedList | sorted | delete | 0.028734
HashTable | shuffled | insert | 0.013259
HashTable | shuffled | find | 0.000109
HashTable | shuffled | delete | 0.000079
HashTable | sorted | insert | 0.014760
HashTable | sorted | find | 0.000107
HashTable | sorted | delete | 0.000076
Bst | shuffled | insert | 0.020712
Bst | shuffled | find | 0.000246
Bst | shuffled | delete | 0.000096
Bst | sorted | insert | 3.905296
Bst | sorted | find | 0.029092
Bst | sorted | delete | 0.018350
Результаты:
Структура Режим вставка поиск удаление
LinkedList shuffled 3.798362 0.028610 0.035444
LinkedList sorted 3.117239 0.020465 0.028734
HashTable shuffled 0.013259 0.000109 0.000079
HashTable sorted 0.014760 0.000107 0.000076
Bst shuffled 0.020712 0.000246 0.000096
Bst sorted 3.905296 0.029092 0.018350
График
График сохранён в файл: results_plot.png
Анализ:
ВСТАВКА:
Лучшая: HashTable (0.014010 сек)
Худшая: LinkedList (3.457801 сек)
ПОИСК:
Лучшая: HashTable (0.000108 сек)
Худшая: LinkedList (0.024537 сек)
УДАЛЕНИЕ:
Лучшая: HashTable (0.000077 сек)
Худшая: LinkedList (0.032089 сек)
Вывод:
Для вставок, поиска и удаления лучше всего использовать HashTable как для отсортированных, так и для неотсортированных данных
BST неплох для отсортированных данных, но всё равно хуже HashTable
LinkedList показал худшие результаты
HashTable - оптимальный выбор для телефонного справочника

121
SimonovaMS/analyz.py Normal file
View File

@ -0,0 +1,121 @@
import csv
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
import os
report_file = open("analys_report.txt", "w", encoding="utf-8")
data = defaultdict(lambda: defaultdict(dict))
with open("C:/Users/Honor/Documents/dep2k/lab_inf_1/data/results.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
header = next(reader)
print(f"{header}")
report_file.write(f"{header}\n")
for row in reader:
if len(row) >= 4:
struct = row[0] # LinkedList, HashTable, Bst
mode = row[1] # shuffled или sorted
op = row[2] # insert, find, delete
time_val = float(row[3])
data[struct][mode][op] = time_val
print(f"{struct} | {mode} | {op} | {time_val:.6f}")
report_file.write(f"{struct} | {mode} | {op} | {time_val:.6f}\n")
op_names = {
'insert': 'вставка',
'find': 'поиск',
'delete': 'удаление'
}
structures = ["LinkedList", "HashTable", "Bst"]
modes = ["shuffled", "sorted"]
operations = ["insert", "find", "delete"]
print("Результаты:")
report_file.write("\nРезультаты:\n")
print(f"{'Структура':<15} {'Режим':<10} {'вставка':<15} {'поиск':<15} {'удаление':<15}")
report_file.write(f"{'Структура':<15} {'Режим':<10} {'вставка':<15} {'поиск':<15} {'удаление':<15}\n")
for struct in structures:
for mode in modes:
insert_time = data[struct][mode]['insert']
find_time = data[struct][mode]['find']
delete_time = data[struct][mode]['delete']
print(f"{struct:<15} {mode:<10} {insert_time:<15.6f} {find_time:<15.6f} {delete_time:<15.6f}")
report_file.write(f"{struct:<15} {mode:<10} {insert_time:<15.6f} {find_time:<15.6f} {delete_time:<15.6f}\n")
#графики
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
for idx, op in enumerate(operations):
ax = axes[idx]
x = np.arange(len(structures))
width = 0.35
shuffled_vals = [data[s]["shuffled"][op] for s in structures]
sorted_vals = [data[s]["sorted"][op] for s in structures]
bars1 = ax.bar(x - width/2, shuffled_vals, width, label='shuffled', color='orange', alpha=0.8)
bars2 = ax.bar(x + width/2, sorted_vals, width, label='sorted', color='cyan', alpha=0.8)
ax.set_xlabel('Структура')
ax.set_ylabel('Время (сек)')
ax.set_title(f'{op_names[op]}')
ax.set_xticks(x)
ax.set_xticklabels(structures, rotation=45)
ax.legend()
ax.set_yscale('log')
for bar in bars1:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height,
f'{height:.3f}', ha='center', va='bottom', fontsize=8)
for bar in bars2:
height = bar.get_height()
ax.text(bar.get_x() + bar.get_width()/2, height,
f'{height:.3f}', ha='center', va='bottom', fontsize=8)
plt.tight_layout()
plot_filename = "results_plot.png"
plt.savefig('results_plot.png', dpi=150)
plt.show()
report_file.write("График\n")
report_file.write(f"График сохранён в файл: {plot_filename}\n")
print("Анализ:")
report_file.write("\nАнализ:\n")
for op in operations:
print(f"\n{op_names[op].upper()}:")
report_file.write(f"\n{op_names[op].upper()}:\n")
# Среднее по двум режимам
avg_times = []
for s in structures:
avg = (data[s]["shuffled"][op] + data[s]["sorted"][op]) / 2
avg_times.append((s, avg))
avg_times.sort(key=lambda x: x[1])
print(f" Лучшая: {avg_times[0][0]} ({avg_times[0][1]:.6f} сек)")
print(f" Худшая: {avg_times[-1][0]} ({avg_times[-1][1]:.6f} сек)")
report_file.write(f" Лучшая: {avg_times[0][0]} ({avg_times[0][1]:.6f} сек)\n")
report_file.write(f" Худшая: {avg_times[-1][0]} ({avg_times[-1][1]:.6f} сек)\n")
print("Вывод:")
report_file.write("\nВывод:\n")
print("Для вставок, поиска и удаления лучше всего использовать HashTable как для отсортированных, так и для неотсортированных данных")
print("BST неплох для отсортированных данных, но всё равно хуже HashTable")
print("LinkedList показал худшие результаты")
print("HashTable - оптимальный выбор для телефонного справочника")
report_file.write("Для вставок, поиска и удаления лучше всего использовать HashTable как для отсортированных, так и для неотсортированных данных\n")
report_file.write("BST неплох для отсортированных данных, но всё равно хуже HashTable\n")
report_file.write("LinkedList показал худшие результаты\n")
report_file.write("HashTable - оптимальный выбор для телефонного справочника\n")
report_file.close()

29
SimonovaMS/generator.py Normal file
View File

@ -0,0 +1,29 @@
import random
from typing import List, Tuple
def generate_data(n=10000):
records = []
for i in range(n):
name = f"User_{i:05d}"
phone = f"8{random.randint(900,999)}{random.randint(100,999)}{random.randint(0,9)}{random.randint(0,9)}{random.randint(0,9)}{random.randint(0,9)}"
records.append((name,phone))
records_shuffled = records.copy()
random.shuffle(records_shuffled)
records_sorted = sorted(records, key=lambda x:x[0])
return records_shuffled, records_sorted
def generate_search(records, exist_count=100, no_exist_count=10):
exist_names = [name for name, _ in records]
select_exist = random.sample(exist_names, min(exist_count, len(exist_names)))
no_exist_count=[f"None_{i:05d}" for i in range(no_exist_count)]
return select_exist + no_exist_count
def generate_delete(records, count=50):
names = [name for name, _ in records]
return random.sample(names, min(count, len(names)))

View File

@ -0,0 +1,200 @@
# experiments.py
import time
import csv
from typing import List, Dict
from maze_model import Maze
from maze_builder import TextFileMazeBuilder
from pathfinding_strategies import BFSStrategy, DFSStrategy, AStarStrategy
from maze_solver import MazeSolver, SearchStats
class ExperimentRunner:
def __init__(self):
self.builder = TextFileMazeBuilder()
self.strategies = [
BFSStrategy(),
DFSStrategy(),
AStarStrategy(),
]
self.results: List[Dict] = []
def create_test_maze_file(self, filename: str, maze_data: List[str]) -> None:
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(maze_data))
def generate_simple_maze(self) -> List[str]:
maze = [
"S E",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" "
]
return maze
def generate_complex_maze(self, size: int = 50) -> List[str]:
import random
random.seed(42)
maze = []
for y in range(size):
row = []
for x in range(size):
if (x == 0 and y == 0):
row.append('S')
elif (x == size - 1 and y == size - 1):
row.append('E')
elif random.random() < 0.3: # 30% стен
row.append('#')
else:
row.append(' ')
maze.append(''.join(row))
for i in range(size):
if maze[i][0] == '#':
row = list(maze[i])
row[0] = ' '
maze[i] = ''.join(row)
if maze[0][i] == '#':
row = list(maze[0])
row[i] = ' '
maze[0] = ''.join(row)
return maze
def generate_empty_maze(self, size: int = 50) -> List[str]:
maze = []
for y in range(size):
row = []
for x in range(size):
if x == 0 and y == 0:
row.append('S')
elif x == size - 1 and y == size - 1:
row.append('E')
else:
row.append(' ')
maze.append(''.join(row))
return maze
def generate_no_exit_maze(self, size: int = 20) -> List[str]:
maze = []
for y in range(size):
row = []
for x in range(size):
if x == 0 and y == 0:
row.append('S')
elif x == size - 1 and y == size - 1:
row.append('#') # Выход заблокирован
else:
row.append('#') # Всё стены
maze.append(''.join(row))
# выход в тупике
row = list(maze[size - 1])
row[size - 1] = 'E'
maze[size - 1] = ''.join(row)
return maze
def run_experiment(self, maze_name: str, maze_data: List[str],
num_runs: int = 5) -> List[Dict]:
filename = f"test_{maze_name}.txt"
self.create_test_maze_file(filename, maze_data)
maze = self.builder.build_from_file(filename)
results = []
for strategy in self.strategies:
solver = MazeSolver(maze, strategy)
times = []
path_lengths = []
for run in range(num_runs):
stats = solver.solve()
times.append(stats.time_ms)
path_lengths.append(stats.path_length)
avg_time = sum(times) / len(times)
avg_path_length = sum(path_lengths) / len(path_lengths)
result = {
'maze': maze_name,
'strategy': strategy.name,
'avg_time_ms': round(avg_time, 3),
'min_time_ms': round(min(times), 3),
'max_time_ms': round(max(times), 3),
'path_length': int(avg_path_length) if avg_path_length else 0,
'path_found': avg_path_length > 0
}
results.append(result)
print(f"{maze_name} - {strategy.name}: "
f"{avg_time:.3f} мс, путь: {int(avg_path_length)}")
return results
def run_all_experiments(self):
experiments = [
("simple_10x10", self.generate_simple_maze()),
("complex_50x50", self.generate_complex_maze(50)),
("large_100x100", self.generate_complex_maze(100)),
("empty_50x50", self.generate_empty_maze(50)),
("no_exit_20x20", self.generate_no_exit_maze(20))
]
all_results = []
for name, data in experiments:
print(f"\n Лабиринт: {name} ---")
results = self.run_experiment(name, data)
all_results.extend(results)
self.save_to_csv(all_results, "experiment_results.csv")
return all_results
def save_to_csv(self, results: List[Dict], filename: str):
if not results:
return
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = results[0].keys()
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(results)
def print_analysis(results: List[Dict]):
# Группировка
mazes = set(r['maze'] for r in results)
for maze in sorted(mazes):
print(f"\nЛабиринт: {maze}")
print("-" * 40)
maze_results = [r for r in results if r['maze'] == maze]
#по времени
sorted_results = sorted(maze_results, key=lambda x: x['avg_time_ms'])
for r in sorted_results:
status = "" if r['path_found'] else ""
print(f" {status} {r['strategy']:8} | "
f"Время: {r['avg_time_ms']:8.3f} мс | "
f"Путь: {r['path_length']:4} шагов")
# Определяем лучший
fastest = sorted_results[0]
print(f"\n → Самый быстрый: {fastest['strategy']} "
f"({fastest['avg_time_ms']:.3f} мс)")

146
SimonovaMS/lab2/main.py Normal file
View File

@ -0,0 +1,146 @@
import sys
from maze_builder import TextFileMazeBuilder
from pathfinding_strategies import BFSStrategy, DFSStrategy, AStarStrategy
from maze_solver import MazeSolver
from visualization import ConsoleView, GameController, EventType
from experiments import ExperimentRunner, print_analysis
from analysis import plot_results
def create_sample_maze():
sample_maze = [
"S ##### ",
"# # ### ",
"# # # # ",
"# # ### # ",
"# # # ",
"### # ### ",
"# # # ",
"# ####### ",
"# E ",
"##########"
]
filename = "sample_maze.txt"
with open(filename, 'w', encoding='utf-8') as f:
f.write('\n'.join(sample_maze))
return filename
def interactive_mode():
builder = TextFileMazeBuilder()
filename = create_sample_maze()
try:
maze = builder.build_from_file(filename)
print(f"Лабиринт загружен: {maze.width}x{maze.height}")
except Exception as e:
print(f"Ошибка загрузки: {e}")
return
view = ConsoleView()
controller = GameController(maze, view)
strategies = {
'1': BFSStrategy(),
'2': DFSStrategy(),
'3': AStarStrategy(),
}
print("\nДоступные алгоритмы поиска пути:")
print(" 1. BFS (поиск в ширину) - кратчайший путь")
print(" 2. DFS (поиск в глубину) - быстрый, не оптимальный")
print(" 3. A* - оптимальный с эвристикой")
# Выбор стратегии
while True:
choice = input("\nВыберите алгоритм (1-3): ").strip()
if choice in strategies:
strategy = strategies[choice]
break
print("Неверный выбор. Попробуйте снова.")
# Поиск пути
print(f"\nИспользуем: {strategy.name}")
print("Поиск пути...")
solver = MazeSolver(maze, strategy)
stats = solver.solve()
if stats.path_found:
print(f" Путь найден! Победа! Длина: {stats.path_length} шагов")
print(f" Время: {stats.time_ms:.3f} мс")
path = strategy.find_path(maze, maze.start, maze.exit)
controller.set_path(path)
# Интерактивное управление
print("\nДемонстрация паттерна Command:")
print(" Используйте W/A/S/D для перемещения")
print(" Нажмите U для отмены последнего хода")
print(" Нажмите Q для выхода")
print("\nТочка '.' показывает найденный путь")
print("Буква 'P' показывает текущую позицию игрока")
controller._render()
while True:
key = input("\n> ").lower()
if key == 'q':
break
elif key == 'w':
from visualization import Direction
controller.move(Direction.UP)
elif key == 's':
from visualization import Direction
controller.move(Direction.DOWN)
elif key == 'a':
from visualization import Direction
controller.move(Direction.LEFT)
elif key == 'd':
from visualization import Direction
controller.move(Direction.RIGHT)
elif key == 'u':
controller.undo()
print("Ход отменён!")
else:
print("Команды: W(вверх), S(вниз), A(влево), D(вправо), U(отмена), Q(выход)")
else:
print("Путь не найден, грустно")
def experimental_mode():
print("эксперименты")
print("Запуск экспериментов на лабиринтах разной сложности...")
runner = ExperimentRunner()
results = runner.run_all_experiments()
print_analysis(results)
#графики
plot_results(results)
def main():
print("\nВыберите режим работы:")
print(" 1. Интерактивный режим (с визуализацией)")
print(" 2. Экспериментальный режим (замеры производительности)")
print(" 3. Выход")
choice = input("\nВаш выбор (1-3): ").strip()
if choice == '1':
interactive_mode()
elif choice == '2':
experimental_mode()
else:
print("Adios!")
sys.exit(0)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,65 @@
from abc import ABC, abstractmethod
from typing import Tuple
import os
from maze_model import Maze, Cell
class MazeBuilder(ABC):
@abstractmethod
def build_from_file(self, filename: str) -> Maze:
pass
class TextFileMazeBuilder(MazeBuilder):
def build_from_file(self, filename: str) -> Maze:
if not os.path.exists(filename):
raise FileNotFoundError(f"Файл {filename} не найден..")
with open(filename, 'r', encoding='utf-8') as file:
lines = [line.rstrip('\n') for line in file.readlines()]
if not lines:
raise ValueError("Пусто(")
height = len(lines)
width = len(lines[0]) if lines else 0
for i, line in enumerate(lines):
if len(line) != width:
raise ValueError(f"Лабиринт не прямоугольный, что-то не так с размерами!")
maze = Maze(width, height)
start_found = False
exit_found = False
for y, line in enumerate(lines):
for x, char in enumerate(line):
cell = Cell(x, y)
if char == '#':
cell.is_wall = True
elif char == 'S':
cell.is_start = True
cell.is_wall = False
maze.start = cell
start_found = True
elif char == 'E':
cell.is_exit = True
cell.is_wall = False
maze.exit = cell
exit_found = True
elif char == ' ':
cell.is_wall = False
else:
raise ValueError(f"Недопустимый символ-'{char}' в позиции ({x}, {y}), уберите его")
maze.set_cell(x, y, cell)
if not start_found:
raise ValueError("В лабиринте нет начала")
if not exit_found:
raise ValueError("В лабиринте нет конца")
return maze

View File

@ -0,0 +1,67 @@
# maze_model.py
from __future__ import annotations
from typing import List, Optional
from dataclasses import dataclass
@dataclass
class Cell:
x: int
y: int
is_wall: bool = False
is_start: bool = False
is_exit: bool = False
def is_passable(self) -> bool:
return not self.is_wall
def __hash__(self) -> int:
return hash((self.x, self.y))
def __eq__(self, other) -> bool:
if not isinstance(other, Cell):
return False
return self.x == other.x and self.y == other.y
class Maze:
def __init__(self, width: int, height: int):
self.width = width
self.height = height
self._cells: List[List[Cell]] = []
self.start: Optional[Cell] = None
self.exit: Optional[Cell] = None
for y in range(height):
row = []
for x in range(width):
row.append(Cell(x, y))
self._cells.append(row)
def set_cell(self, x: int, y: int, cell: Cell) -> None:
if 0 <= x < self.width and 0 <= y < self.height:
self._cells[y][x] = cell
def get_cell(self, x: int, y: int) -> Optional[Cell]:
if 0 <= x < self.width and 0 <= y < self.height:
return self._cells[y][x]
return None
def get_neighbors(self, cell: Cell) -> List[Cell]:
neighbors = []
# вверх, вниз, влево, вправо
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
for dx, dy in directions:
neighbor = self.get_cell(cell.x + dx, cell.y + dy)
if neighbor and neighbor.is_passable():
neighbors.append(neighbor)
return neighbors
def get_all_cells(self) -> List[Cell]:
cells = []
for row in self._cells:
cells.extend(row)
return cells

View File

@ -0,0 +1,52 @@
import time
from dataclasses import dataclass
from typing import List, Optional
from maze_model import Maze, Cell
from pathfinding_strategies import PathFindingStrategy
@dataclass
class SearchStats:
time_ms: float
visited_cells: int
path_length: int
path_found: bool
strategy_name: str
class MazeSolver:
def __init__(self, maze: Maze, strategy: Optional[PathFindingStrategy] = None):
self.maze = maze
self._strategy = strategy
def set_strategy(self, strategy: PathFindingStrategy) -> None:
self._strategy = strategy
def solve(self) -> SearchStats:
if self._strategy is None:
raise ValueError("Стратегии нет!")
if self.maze.start is None or self.maze.exit is None:
raise ValueError("Лабиринт не содержит начала или конца")
start_time = time.perf_counter()
if hasattr(self._strategy, '_find_path_with_stats'):
path, visited = self._strategy._find_path_with_stats(
self.maze, self.maze.start, self.maze.exit
)
else:
path = self._strategy.find_path(
self.maze, self.maze.start, self.maze.exit
)
visited = 0
end_time = time.perf_counter()
return SearchStats(
time_ms=(end_time - start_time) * 1000,
visited_cells=visited,
path_length=len(path) if path else 0,
path_found=len(path) > 0,
strategy_name=self._strategy.name
)

Binary file not shown.

View File

@ -0,0 +1,142 @@
from abc import ABC, abstractmethod
from typing import List, Dict, Optional, Tuple
from collections import deque
import heapq
from maze_model import Maze, Cell
class PathFindingStrategy(ABC):#интерфейс стратегии поиска
@abstractmethod
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
pass
@property
@abstractmethod
def name(self) -> str:
pass
class BFSStrategy(PathFindingStrategy):#в ширину
@property
def name(self) -> str:
return "BFS"
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
path, _ = self._find_path_with_stats(maze, start, exit_cell)
return path
def _find_path_with_stats(self, maze: Maze, start: Cell, exit_cell: Cell) -> tuple:
if start == exit_cell:
return [start], 1
from collections import deque
queue = deque([start])
visited = {start}
parent = {start: None}
while queue:
current = queue.popleft()
if current == exit_cell:
return self._reconstruct_path(parent, exit_cell), len(visited)
for neighbor in maze.get_neighbors(current):
if neighbor not in visited:
visited.add(neighbor)
parent[neighbor] = current
queue.append(neighbor)
return [], len(visited)
def _reconstruct_path(self, parent: dict, exit_cell: Cell) -> List[Cell]:
path = []
current = exit_cell
while current is not None:
path.append(current)
current = parent[current]
return list(reversed(path))
class DFSStrategy(PathFindingStrategy):#в глубину
@property
def name(self) -> str:
return "DFS"
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
path, _ = self._find_path_with_stats(maze, start, exit_cell)
return path
def _find_path_with_stats(self, maze: Maze, start: Cell, exit_cell: Cell) -> tuple:
if start == exit_cell:
return [start], 1
stack = [(start, [start])]
visited = {start}
while stack:
current, path = stack.pop()
if current == exit_cell:
return path, len(visited)
for neighbor in maze.get_neighbors(current):
if neighbor not in visited:
visited.add(neighbor)
stack.append((neighbor, path + [neighbor]))
return [], len(visited)
class AStarStrategy(PathFindingStrategy): #A*
@property
def name(self) -> str:
return "A*"
def _heuristic(self, cell: Cell, target: Cell) -> int:
return abs(cell.x - target.x) + abs(cell.y - target.y)
def find_path(self, maze: Maze, start: Cell, exit_cell: Cell) -> List[Cell]:
path, _ = self._find_path_with_stats(maze, start, exit_cell)
return path
def _find_path_with_stats(self, maze: Maze, start: Cell, exit_cell: Cell) -> tuple:
import heapq
if start == exit_cell:
return [start], 1
counter = 0
open_set = [(0, counter, start)]
came_from = {}
visited = {start}
g_score = {start: 0}
f_score = {start: self._heuristic(start, exit_cell)}
while open_set:
current = heapq.heappop(open_set)[2]
if current == exit_cell:
return self._reconstruct_path(came_from, exit_cell), len(visited)
for neighbor in maze.get_neighbors(current):
visited.add(neighbor)
tentative_g = g_score[current] + 1
if neighbor not in g_score or tentative_g < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g
f_score[neighbor] = tentative_g + self._heuristic(neighbor, exit_cell)
counter += 1
heapq.heappush(open_set, (f_score[neighbor], counter, neighbor))
return [], len(visited)
def _reconstruct_path(self, came_from: dict, current: Cell) -> List[Cell]:
path = [current]
while current in came_from:
current = came_from[current]
path.append(current)
return list(reversed(path))

View File

@ -0,0 +1,10 @@
S #####
# # ###
# # # #
# # ### #
# # #
### # ###
# # #
# #######
# E
##########

View File

@ -0,0 +1,50 @@
S
## # # ## ## ## # # ### #
# # # # # # # # # # # # # # # #
## ### # ## ## ## # ## ## #
# # # # ## # # ## ## # # #
# ### # # # ### # # # # ## # ##
## ### # # # # # ### #
# # ## # # # ## ##
# ## #### # # # # # # ##
## #### ## # # # ## # #
# # # # # ### #### # # # ##
# # # # # # # # ## ##
# ## ##### ## ###### # #
## # ## # # ## #### ##
## ## ## ## ## # # #
# # # ## # # # # #
## # # # # # #
## # # # # ## # # ### # # # #
# # # # ## ## # # #
# ### ## # # # # # #
# ## # ## # ## # # #### ## # ## #
# ## ## # # # # # # ##
# # ## # ## # # # # #
# # # # # # # ### # # # ## ##
# # # ### # ## ## # #
### ## # # ## # #
## ### # # # # # # #
## # # # # # ## # # ## # ### #
# # # ## # # # ## # # #
### # # # # # # # #
# ## ## ## # # # #
### # # # # #### # #
# ## # ### # # #### # #
# # # # # # # # ##
# # # # # # # ## # ##
# ## # ### ## ## # # # #
# # # # # # # # # # ##
## # # ## ### # ## # # ###
# # # # # ## # # # # # #
# #### # # # #### # ## # #
# # # # ### # ## #
# # # # # # ### # # # #
## # # # # # # #### # #
### # ## ## # ### # #
## # ## ## ### # # # # # # #
### ## # # # # # #
# # # # ## ## # #
# # # ### # # # # # ## # #
# ### # # # # # ## ## ## # ##
# # # # ##### # ## # # #E

View File

@ -0,0 +1,50 @@
S
E

View File

@ -0,0 +1,100 @@
S
# # # # # # # # # # # # # # # # ## ### # ## ## ## # ## ## #
# # # # ## # # ## ## # # # # # ### # # # ### # # # # ## # ##
## ### # # # # # ### # # # ## # # # ## ##
# ## #### # # # # # # ## ## #### ## # # # ## # #
# # # # # ### #### # # # ## # # # # # # # # # ## ##
# ## ##### ## ###### # # ## # ## # # ## #### ##
## ## ## ## ## # # # # # # ## # # # # #
## # # # # # # ## # # # # ## # # ### # # # #
# # # # ## ## # # # # ### ## # # # # # #
# ## # ## # ## # # #### ## # ## # # # ## ## # # # # # # ##
# # ## # ## # # # # ### # # # # # # ### # # # ## ##
# # # ### # ## ## # # ### ## # # ## # #
## ### # # # # # # # # ## # # # # # ## # # ## # ### #
# # # ## # # # ## # # # #### # # # # # # # #
# ## ## ## # # # # ### # # # # #### # #
# ## # ### # # #### # # # # # # # # # # ##
# # # # # # # ## # ### # ## # ### ## ## # # # #
# # # # # # # # # # ### ## # # ## ### # ## # # ###
# # # # # ## # # # # # # # #### # # # #### # ## # #
# # # # ### # ## # # # # # # # ### # # # #
## # # # # # # #### # # # ### # ## ## # ### # #
## # ## ## ### # # # # # # # ### ## # # # # # #
# # # # ## ## # # # # # ### # # # # # ## # #
# ### # # # # # ## ## ## # ## # # # # ##### # ## # # #
# # # # # # ## ## # # # # # # # # # # ## # ## # # # # # # ##
### ## # # ##### # # # # ## # # ## # # ## #
# # # # # ## # # # ## # ## # # # # # # ### # ## ### ##
### # ## # # # ## # # ## # # # # #### # ## #### # # # # # # #
# # # ### # ## # # ## # # # # # # # # # # ###### #
## # ## # # # #### #### # # ##### # # # ### # # # # #
# # # # ## ### # # # # # # # ## # # ## # # ## # # # #
# # # ## # # ### # ## # # # # #### # # ## # ##
## # ## # # ## # # # # # ## # # # # # # # # # # # # ###### #
## # # ## ### # #### # # # # # # # # # # # # # ## # # # # #
## # # # ## # ## # # # ### # # # # # # # # # #
# # # # ## # ### # # # # # ## ## ## # # ## # ###
### # # # # # # ## # # ## ## # # # # # #
## ## ## ### # # ### # # # # ### # # # # #
# # ## # # # ### ## ## ## ## # # ### # ## # # # # ## ## #
# # # # ## # # # ## # # # # ## # ### #### # ## ##
### ### # # # ### ### # # ## # # # ### ## # ## #
# ## # # # ### #### # # # # ### # # # ## ### ## # #
#### # ### ## # # # # # # # # ### # # # # ## # ### ###
# # # # # # # # # # ## ### ## ### # ## # # # ## # #### #
## # # # # # # # # # # # ### # # # # # ## # # #
# # ## # # # # ## # # # # ## ## ## # # ## # ## # # ## #
## # # ## # # # # ### # # # # # # # ## # # # ## # ### ## # #
# # ## # ## ### ## # # # # ## # # # # # #
# ## # # ### # # # # # ## # # # # # ## # ## # # #
# # ## # ### # ## # # ## # # # # # # # #
# # # ## #### # # ### # ## # # ## # # ##
# # # ## # ### # ## ## # # # # ### # # # #
# # # # # # ## # ## ## ### ### # # ## # # # ## # #
# ## # # ### ##### # # # # ## # # # # # ## # # #
# # # ## # # ## # ## ## # ## # ### # # # # ## ##
# ### # ## ### # # ## # # # # # # # # # # # ## ## # #
# # # # # # # # ## # # # # # # # # # # # ## # # # ## # #
# # # ## # # ## # # ## # # # ### ### # # # # # # #
## # ## # # # # # # # ## # # ## # ### ### # # ## ##
# ## # # #### # # # # ##### # ## #### # # # # # # ####
## # ### ### # ## # ## # # ## # # # # # # ## #### # ## # #
# # # ## # # # # # # # ## # # # # # #
## # ## ## # ### #### # # # # ## # ## # ## #
# # # ## ## # ## # ## # # # # # # ##
# # # # # # ### ## ### # ## # # #### # # # ##### #
## ## # # # ## # ## ## # # # # # # # # # # ##
##### # ### # ## # # # ## # ### #### # # ### # ## #
### ## ## # ## # ### # ## ### # ## ## ## ## # # # #
# # ### # ## # # ## # # # # ## ## # ## # ## #
# ## # ## # ## # ## # # # # # # # # #
# ## # # # ####### # ## ## ## # # # # # # # # # ## #
# # # # ## # # ### # # # ## #### # # # # # #
### # ### # ### # ### ## # # # # # ## # # # # # # # #
# # ##### # ## ##### #### ## # # # ## # ## # # ## #
# ### ## ## # ##### # ## # # # # # #
# # # ## ## # ## ## ## # ## # ## #### # # ## # # # # # ##
# # ## # # # #### # # ## # ## ## # # ## # ## ## # # ## # #
# # # #### # ## # # # ## ### ## #### # # # # #
## ### # # # ## # # # # # # # ## # ## ###
# ## # ## # # # # # # # # # # # ### # # # ## #
# ## ## # #### # ## # # # # # # #
# # ## ### # # # ## ## # ## # # # ## # # # # # ####
# # ## ### # # ## ## # # # # ### # # ## # # # ##
## # # # # ## ## # ## # # #### # # # #
# ## # # # # # # ### ## # #### # # ## # # # # ### ## # ##
### # ## ## # # # # # # ## # # # ## # #### # ##### #
# # # # # # # ## ## ### # ### ### # # #### # # # # ## # ##
# # # #### # # # # ## # # ## # # ## # # ## # ##
# # # ## ## # ## # # # ## ## # ### ## # ## # # # # # # #
## # # # ## # ## ## ## # # ## # # # # # ## # # # #
### # # # ## # # # # # # # # # # # # ## # # # ##
# # # ## # # # # ## # # ## # # # # # # ## # # # #
# # # ## # ## # ### # # ### # ## # # # ## # ### #
## # # # ## # # ## # # # ## # # #### ## # # # ### #
# #### ## ### ### # # ### # # ## # # # ### # ####### # ##
# # ## ## ### ## ### # # # # # # # # # # #
# ### # ## # ### # ## ## ## # # # # # # # ## ## # ###
# ## ### ## # # # # # # # # # # # # ###
# # # # # ## ### # # ## ## ## ### # # # # # # ## # # E

View File

@ -0,0 +1,20 @@
S###################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
####################
###################E

View File

@ -0,0 +1,10 @@
S E

View File

@ -0,0 +1,160 @@
from abc import ABC, abstractmethod
from typing import List, Optional, Set
from enum import Enum
from maze_model import Maze, Cell
class EventType(Enum):
PATH_FOUND = "path_found"
MOVE = "move"
MAZE_LOADED = "maze_loaded"
SOLVE_START = "solve_start"
SOLVE_END = "solve_end"
class Observer(ABC):
@abstractmethod
def update(self, event_type: EventType, data: any) -> None:
pass
class ConsoleView(Observer):
def __init__(self):
self.last_path: Optional[List[Cell]] = None
def update(self, event_type: EventType, data: any) -> None:
if event_type == EventType.MAZE_LOADED:
print("Лабиринт загружен")
elif event_type == EventType.SOLVE_START:
print("Начинается поиск пути...")
elif event_type == EventType.SOLVE_END:
print(f"Поиск завершён. Статистика: {data}")
elif event_type == EventType.PATH_FOUND:
self.last_path = data
def render(self, maze: Maze, player_pos: Optional[Cell] = None,
path: Optional[List[Cell]] = None) -> None: #рисует лаб
import os
os.system('cls' if os.name == 'nt' else 'clear')
path_set = set(path) if path else set()
# Верх
print("" + "" * maze.width + "")
for y in range(maze.height):
line = ""
for x in range(maze.width):
cell = maze.get_cell(x, y)
if player_pos and player_pos.x == x and player_pos.y == y:
line += "P"
elif cell == maze.start:
line += "S"
elif cell == maze.exit:
line += "E"
elif cell is not None and cell.is_wall:
line += "#"
elif path and cell in path_set:
line += "."
else:
line += " "
line += ""
print(line)
# Низ
print("" + "" * maze.width + "")
if path:
print(f"\nПуть найден! Длина: {len(path)} шагов")
elif path == []:
print("\nПуть не найден:(")
class Player:
def __init__(self, start_cell: Cell):
self.current_cell = start_cell
def move_to(self, cell: Cell) -> None:
self.current_cell = cell
def get_position(self) -> Cell:
return self.current_cell
class Direction(Enum):
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
class Command(ABC):
@abstractmethod
def execute(self) -> None:
pass
@abstractmethod
def undo(self) -> None:
pass
class MoveCommand(Command):
def __init__(self, player: Player, maze: Maze, direction: Direction):
self.player = player
self.maze = maze
self.direction = direction
self.previous_cell = player.current_cell
def execute(self) -> None:
dx, dy = self.direction.value
new_x = self.player.current_cell.x + dx
new_y = self.player.current_cell.y + dy
new_cell = self.maze.get_cell(new_x, new_y)
if new_cell and new_cell.is_passable():
self.previous_cell = self.player.current_cell
self.player.move_to(new_cell)
return True
return False
def undo(self) -> None:
self.player.move_to(self.previous_cell)
class GameController:
def __init__(self, maze: Maze, view: ConsoleView):
if maze.start is None:
raise ValueError("Лабиринт не имеет стартовой клетки")
self.maze = maze
self.view = view
self.player = Player(maze.start)
self.command_history: List[Command] = []
self.found_path: Optional[List[Cell]] = None
def move(self, direction: Direction) -> bool:
command = MoveCommand(self.player, self.maze, direction)
if command.execute():
self.command_history.append(command)
self._render()
return True
return False
def undo(self) -> None:
if self.command_history:
command = self.command_history.pop()
command.undo()
self._render()
def set_path(self, path: List[Cell]) -> None:
self.found_path = path
self._render()
def _render(self) -> None:
self.view.render(self.maze, self.player.get_position(), self.found_path)

247
SimonovaMS/phonebook.py Normal file
View File

@ -0,0 +1,247 @@
import time
import csv
import random
from functools import lru_cache
from operator import index
#LinkedListPhoneBook
def create_node(name, phone):
return {'name': name, 'phone': phone, 'next': None}
def ll_insert(head, name, phone):
new_node = create_node(name,phone)
if head is None:
return new_node
current = head
while current['next'] is not None:
if current['next']['name'] == name:
new_node['next'] = current['next']['next']
current['next']=new_node
return head
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']
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
#хеш=тфблица
def create_buckets(size=1000):
return [None] * size
def hash_function(name, buckest_size):
hash_value = 0
for char in name:
hash_value = (hash_value * 31 + ord(char)) % buckest_size
return hash_value
def ht_insert(buckets, name, phone):
index = hash_function(name, len(buckets))
buckets[index] = ll_insert(buckets[index], name, phone)
def ht_find(buckets, name):
index = hash_function(name, len(buckets))
return ll_find(buckets[index], name)
def ht_delete(buckets, name):
index = hash_function(name, len(buckets))
buckets[index] = ll_delete(buckets[index], name)
def ht_list_all(buckets):
records = []
for bucket in buckets:
current = bucket
while current is not None:
records.append((current['name'], current['phone']))
current = current['next']
records.sort(key=lambda x:x[0])
return records
#bts
def create_bst_node(name, phone):
return {'name': name, 'phone': phone, 'left': None, 'right': None}
def bst_insert(root, name, phone):
new_node = create_bst_node(name, phone)
if root is None:
return new_node
current = root
while True:
if name == current['name']:
current['phone'] = phone
return root
elif name < current['name']:
if current['left'] is None:
current['left'] = new_node
return root
current = current['left']
else:
if current['right'] is None:
current['right'] = new_node
return root
current = current['right']
def bst_find(root, name):
current = root
while current is not None:
if name == current['name']:
return current['phone']
elif name < current['name']:
current=current['left']
else:
current=current['right']
return None
def bst_find_min(node):
current = node
while current['left'] is not None:
current = current['left']
return current
def bst_delete(root, name):
if root is None:
return None
if root['name'] == name:
if root['left'] is None and root['right'] is None:
return None
if root['left'] is None:
return root['right']
if root['right'] is None:
return root['left']
parent = root
min_node = root['right']
while min_node['left']:
parent = min_node
min_node = min_node['left']
root['name'] = min_node['name']
root['phone'] = min_node['phone']
if parent == root:
parent['right'] = min_node['right']
else:
parent['left'] = min_node['right']
return root
parent = None
current = root
while current and current['name'] != name:
parent = current
if name < current['name']:
current = current['left']
else:
current = current['right']
if current is None:
return root
if current['left'] is None and current['right'] is None:
if parent['left'] == current:
parent['left'] = None
else:
parent['right'] = None
elif current['left'] is None:
if parent['left'] == current:
parent['left'] = current['right']
else:
parent['right'] = current['right']
elif current['right'] is None:
if parent['left'] == current:
parent['left'] = current['left']
else:
parent['right'] = current['left']
else:
min_parent = current
min_node = current['right']
while min_node['left']:
min_parent = min_node
min_node = min_node['left']
current['name'] = min_node['name']
current['phone'] = min_node['phone']
if min_parent == current:
min_parent['right'] = min_node['right']
else:
min_parent['left'] = min_node['right']
return root
def bst_list_all(root):
records = []
stack = []
current = root
while stack or current:
while current:
stack.append(current)
current = current['left']
current = stack.pop()
records.append((current['name'], current['phone']))
current = current['right']
return records
def bst_list_all(root):
records =[]
stack = []
current = root
while stack or current is not None:
while current is not None:
stack.append(current)
current=current['left']
current=stack.pop()
records.append((current['name'], current['phone']))
current=current['right']
return records

BIN
SimonovaMS/result_plot.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

211
SimonovaMS/test.py Normal file
View File

@ -0,0 +1,211 @@
import time
import csv
import random
from phonebook import (ll_insert, ll_find, ll_delete, create_buckets, ht_insert, ht_find, ht_delete, bst_insert, bst_find, bst_delete)
from generator import generate_data
def run_exp():
records_shuffled, records_sorted = generate_data(10000)
all_names = [name for name, _ in records_shuffled]
search_names = random.sample(all_names, 100) + [f"None_{i}" for i in range(10)]
delete_names = random.sample(all_names, 50)
results = [["Structura", "shuffled/sorted", "Operation", "Time"]]
times =[]
print('LinkedList - shuffled')
for r in range(5):
head = None
start = time.perf_counter()
for name, phone in records_shuffled:
head = ll_insert(head, name, phone)
times.append(time.perf_counter() - start)
avg = sum(times)/5
results.append(["LinkedList", "shuffled", "insert", avg])
print(f"вставка - {avg:.6f}")
times=[]
for r in range(5):
start = time.perf_counter()
for name in search_names:
ll_find(head, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["LinkedList", "shuffled", "find", avg])
print(f"поиск - {avg:.6f}")
times=[]
for r in range(5):
start = time.perf_counter()
for name in delete_names:
head = ll_delete(head, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["LinkedList", "shuffled", "delete", avg])
print(f"удаление - {avg:.6f}")
print('LinkedList - sorted')
for r in range(5):
head = None
start = time.perf_counter()
for name, phone in records_sorted:
head = ll_insert(head, name, phone)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["LinkedList", "sorted", "insert", avg])
print(f"вставка - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in search_names:
ll_find(head, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["LinkedList", "sorted", "find", avg])
print(f"поиск - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in delete_names:
head = ll_delete(head, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["LinkedList", "sorted", "delete", avg])
print(f"удаление - {avg:.6f}")
print('HashTable - shuffled')
times =[]
for r in range(5):
buckets = create_buckets(1000)
start = time.perf_counter()
for name, phone in records_shuffled:
ht_insert(buckets,name,phone)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["HashTable", "shuffled", "insert", avg])
print(f"вставка - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in search_names:
ht_find(buckets, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["HashTable", "shuffled", "find", avg])
print(f"поиск - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in delete_names:
ht_delete(buckets, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["HashTable", "shuffled", "delete", avg])
print(f"удаление - {avg:.6f}")
print('sorted')
times = []
for r in range(5):
buckets = create_buckets(1000)
start = time.perf_counter()
for name, phone in records_sorted:
ht_insert(buckets, name, phone)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["HashTable", "sorted", "insert", avg])
print(f"вставка - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in search_names:
ht_find(buckets, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["HashTable", "sorted", "find", avg])
print(f"поиск - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in delete_names:
ht_delete(buckets, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["HashTable", "sorted", "delete", avg])
print(f"удаление - {avg:.6f}")
print("BST - shuffled")
times = []
for r in range(5):
root = None
start = time.perf_counter()
for name, phone in records_shuffled:
root = bst_insert(root, name, phone)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["Bst", "shuffled", "insert", avg])
print(f"вставка - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in search_names:
bst_find(root, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["Bst", "shuffled", "find", avg])
print(f"поиск - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in delete_names:
root = bst_delete(root, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["Bst", "shuffled", "delete", avg])
print(f"удаление - {avg:.6f}")
print('sorted')
times = []
for r in range(5):
root = None
start = time.perf_counter()
for name, phone in records_sorted:
root = bst_insert(root, name, phone)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["Bst", "sorted", "insert", avg])
print(f"вставка - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in search_names:
bst_find(root, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["Bst", "sorted", "find", avg])
print(f"поиск - {avg:.6f}")
times = []
for r in range(5):
start = time.perf_counter()
for name in delete_names:
root = bst_delete(root, name)
times.append(time.perf_counter() - start)
avg = sum(times) / 5
results.append(["Bst", "sorted", "delete", avg])
print(f"удаление - {avg:.6f}")
with open("C:/Users/Honor/Documents/dep2k/lab_inf_1/data/results.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerows(results)
if __name__ == "__main__":
run_exp()

View File

View File

View File

View File

View File

View File

View File

@ -1 +0,0 @@
1

View File

@ -1 +0,0 @@
428b

View File

View File

View File

View File

View File

@ -1 +0,0 @@
428

View File

View File

View File

View File

View File

View File

View File

View File

View File

@ -1 +0,0 @@
427

View File

View File

View File

@ -1 +0,0 @@
856

View File

View File

View File

Binary file not shown.

View File

@ -1 +0,0 @@
429

View File

View File

View File

@ -1 +0,0 @@
428b.md

View File

View File

View File

@ -1,2 +0,0 @@
print("Zadanie adin!!11!adin!11!")
print("patch")

View File

@ -1 +0,0 @@
429

View File

@ -1 +0,0 @@
428b

View File

Binary file not shown.

View File

View File

View File

@ -1,6 +0,0 @@
{\rtf1\ansi\ansicpg1251\cocoartf2869
\cocoatextscaling0\cocoaplatform0{\fonttbl}
{\colortbl;\red255\green255\blue255;}
{\*\expandedcolortbl;;}
\paperw11900\paperh16840\margl1440\margr1440\vieww11520\viewh8400\viewkind0
}

Some files were not shown because too many files have changed in this diff Show More