Merge pull request '[1,2] lab1, lab2' (#273) from soldatkinao/2026-rff_mp:soldatkinao into develop

Reviewed-on: UNN/2026-rff_mp#273
This commit is contained in:
AlexanderVah 2026-05-30 11:40:26 +00:00
commit f36e519a20
13 changed files with 977 additions and 0 deletions

Binary file not shown.

View File

@ -0,0 +1,121 @@
Структура,Порядок,Повторение,Операция,Время (с)
LinkedList,shuffled,1,insert,3.1302744999993593
LinkedList,shuffled,1,find,0.005220100050792098
LinkedList,shuffled,1,delete,0.014845799887552857
LinkedList,shuffled,1,list_all,0.0055240001529455185
LinkedList,shuffled,2,insert,3.9573061999399215
LinkedList,shuffled,2,find,0.005903499899432063
LinkedList,shuffled,2,delete,0.012860000133514404
LinkedList,shuffled,2,list_all,0.005526799941435456
LinkedList,shuffled,3,insert,3.934717500116676
LinkedList,shuffled,3,find,0.005851200083270669
LinkedList,shuffled,3,delete,0.015433399938046932
LinkedList,shuffled,3,list_all,0.005478800041601062
LinkedList,shuffled,4,insert,3.927386400057003
LinkedList,shuffled,4,find,0.005423200083896518
LinkedList,shuffled,4,delete,0.013300799997523427
LinkedList,shuffled,4,list_all,0.005344899836927652
LinkedList,shuffled,5,insert,4.010202700039372
LinkedList,shuffled,5,find,0.006096000084653497
LinkedList,shuffled,5,delete,0.013918899931013584
LinkedList,shuffled,5,list_all,0.006746200146153569
LinkedList,sorted,1,insert,4.09783950005658
LinkedList,sorted,1,find,0.0430095000192523
LinkedList,sorted,1,delete,0.01721159997396171
LinkedList,sorted,1,list_all,0.005465000169351697
LinkedList,sorted,2,insert,4.133864999981597
LinkedList,sorted,2,find,0.0456748001743108
LinkedList,sorted,2,delete,0.016983899986371398
LinkedList,sorted,2,list_all,0.002011100063100457
LinkedList,sorted,3,insert,4.122705399990082
LinkedList,sorted,3,find,0.045870000030845404
LinkedList,sorted,3,delete,0.016401699976995587
LinkedList,sorted,3,list_all,0.005049800034612417
LinkedList,sorted,4,insert,3.772368999896571
LinkedList,sorted,4,find,0.02993709989823401
LinkedList,sorted,4,delete,0.011476899962872267
LinkedList,sorted,4,list_all,0.003602599957957864
LinkedList,sorted,5,insert,3.264690199866891
LinkedList,sorted,5,find,0.02624980011023581
LinkedList,sorted,5,delete,0.01183390012010932
LinkedList,sorted,5,list_all,0.0017556999810039997
HashTable,shuffled,1,insert,0.005876099923625588
HashTable,shuffled,1,find,3.350013867020607e-05
HashTable,shuffled,1,delete,3.0100112780928612e-05
HashTable,shuffled,1,list_all,0.004497800022363663
HashTable,shuffled,2,insert,0.007247900124639273
HashTable,shuffled,2,find,2.9999995604157448e-05
HashTable,shuffled,2,delete,2.95999925583601e-05
HashTable,shuffled,2,list_all,0.00580970011651516
HashTable,shuffled,3,insert,0.004507799865677953
HashTable,shuffled,3,find,2.2900057956576347e-05
HashTable,shuffled,3,delete,1.8700025975704193e-05
HashTable,shuffled,3,list_all,0.003462200053036213
HashTable,shuffled,4,insert,0.005082499934360385
HashTable,shuffled,4,find,3.1800009310245514e-05
HashTable,shuffled,4,delete,2.8799986466765404e-05
HashTable,shuffled,4,list_all,0.007747200084850192
HashTable,shuffled,5,insert,0.004538299981504679
HashTable,shuffled,5,find,2.2900057956576347e-05
HashTable,shuffled,5,delete,1.9300030544400215e-05
HashTable,shuffled,5,list_all,0.003729799995198846
HashTable,sorted,1,insert,0.005079899914562702
HashTable,sorted,1,find,5.079992115497589e-05
HashTable,sorted,1,delete,2.550007775425911e-05
HashTable,sorted,1,list_all,0.005039500072598457
HashTable,sorted,2,insert,0.004276499850675464
HashTable,sorted,2,find,4.079984501004219e-05
HashTable,sorted,2,delete,2.110004425048828e-05
HashTable,sorted,2,list_all,0.004337100079283118
HashTable,sorted,3,insert,0.006273699924349785
HashTable,sorted,3,find,3.9400067180395126e-05
HashTable,sorted,3,delete,1.919991336762905e-05
HashTable,sorted,3,list_all,0.0032929000444710255
HashTable,sorted,4,insert,0.004404899897053838
HashTable,sorted,4,find,4.0499959141016006e-05
HashTable,sorted,4,delete,2.0800158381462097e-05
HashTable,sorted,4,list_all,0.006671200040727854
HashTable,sorted,5,insert,0.00421059993095696
HashTable,sorted,5,find,4.0999846532940865e-05
HashTable,sorted,5,delete,2.140016295015812e-05
HashTable,sorted,5,list_all,0.0034396001137793064
BST,shuffled,1,insert,0.015235899947583675
BST,shuffled,1,find,6.360001862049103e-05
BST,shuffled,1,delete,9.159999899566174e-05
BST,shuffled,1,list_all,0.0042282999493181705
BST,shuffled,2,insert,0.016312200110405684
BST,shuffled,2,find,5.859998054802418e-05
BST,shuffled,2,delete,9.659980423748493e-05
BST,shuffled,2,list_all,0.004191800020635128
BST,shuffled,3,insert,0.015240099979564548
BST,shuffled,3,find,5.859998054802418e-05
BST,shuffled,3,delete,8.849985897541046e-05
BST,shuffled,3,list_all,0.0036266997922211885
BST,shuffled,4,insert,0.014052000129595399
BST,shuffled,4,find,5.9300102293491364e-05
BST,shuffled,4,delete,8.119991980493069e-05
BST,shuffled,4,list_all,0.0027294999454170465
BST,shuffled,5,insert,0.013222299981862307
BST,shuffled,5,find,6.059999577701092e-05
BST,shuffled,5,delete,7.970002479851246e-05
BST,shuffled,5,list_all,0.0028162000235170126
BST,sorted,1,insert,5.109697200125083
BST,sorted,1,find,0.05814290000125766
BST,sorted,1,delete,0.027696199947968125
BST,sorted,1,list_all,0.004435899900272489
BST,sorted,2,insert,6.02595020015724
BST,sorted,2,find,0.05516729992814362
BST,sorted,2,delete,0.028573499992489815
BST,sorted,2,list_all,0.003455700119957328
BST,sorted,3,insert,5.749598399968818
BST,sorted,3,find,0.04719489999115467
BST,sorted,3,delete,0.03186570014804602
BST,sorted,3,list_all,0.002738000126555562
BST,sorted,4,insert,5.19493699981831
BST,sorted,4,find,0.052105900133028626
BST,sorted,4,delete,0.028118600137531757
BST,sorted,4,list_all,0.005104599986225367
BST,sorted,5,insert,5.953492499887943
BST,sorted,5,find,0.060425500152632594
BST,sorted,5,delete,0.024722500005736947
BST,sorted,5,list_all,0.004347699927166104
1 Структура Порядок Повторение Операция Время (с)
2 LinkedList shuffled 1 insert 3.1302744999993593
3 LinkedList shuffled 1 find 0.005220100050792098
4 LinkedList shuffled 1 delete 0.014845799887552857
5 LinkedList shuffled 1 list_all 0.0055240001529455185
6 LinkedList shuffled 2 insert 3.9573061999399215
7 LinkedList shuffled 2 find 0.005903499899432063
8 LinkedList shuffled 2 delete 0.012860000133514404
9 LinkedList shuffled 2 list_all 0.005526799941435456
10 LinkedList shuffled 3 insert 3.934717500116676
11 LinkedList shuffled 3 find 0.005851200083270669
12 LinkedList shuffled 3 delete 0.015433399938046932
13 LinkedList shuffled 3 list_all 0.005478800041601062
14 LinkedList shuffled 4 insert 3.927386400057003
15 LinkedList shuffled 4 find 0.005423200083896518
16 LinkedList shuffled 4 delete 0.013300799997523427
17 LinkedList shuffled 4 list_all 0.005344899836927652
18 LinkedList shuffled 5 insert 4.010202700039372
19 LinkedList shuffled 5 find 0.006096000084653497
20 LinkedList shuffled 5 delete 0.013918899931013584
21 LinkedList shuffled 5 list_all 0.006746200146153569
22 LinkedList sorted 1 insert 4.09783950005658
23 LinkedList sorted 1 find 0.0430095000192523
24 LinkedList sorted 1 delete 0.01721159997396171
25 LinkedList sorted 1 list_all 0.005465000169351697
26 LinkedList sorted 2 insert 4.133864999981597
27 LinkedList sorted 2 find 0.0456748001743108
28 LinkedList sorted 2 delete 0.016983899986371398
29 LinkedList sorted 2 list_all 0.002011100063100457
30 LinkedList sorted 3 insert 4.122705399990082
31 LinkedList sorted 3 find 0.045870000030845404
32 LinkedList sorted 3 delete 0.016401699976995587
33 LinkedList sorted 3 list_all 0.005049800034612417
34 LinkedList sorted 4 insert 3.772368999896571
35 LinkedList sorted 4 find 0.02993709989823401
36 LinkedList sorted 4 delete 0.011476899962872267
37 LinkedList sorted 4 list_all 0.003602599957957864
38 LinkedList sorted 5 insert 3.264690199866891
39 LinkedList sorted 5 find 0.02624980011023581
40 LinkedList sorted 5 delete 0.01183390012010932
41 LinkedList sorted 5 list_all 0.0017556999810039997
42 HashTable shuffled 1 insert 0.005876099923625588
43 HashTable shuffled 1 find 3.350013867020607e-05
44 HashTable shuffled 1 delete 3.0100112780928612e-05
45 HashTable shuffled 1 list_all 0.004497800022363663
46 HashTable shuffled 2 insert 0.007247900124639273
47 HashTable shuffled 2 find 2.9999995604157448e-05
48 HashTable shuffled 2 delete 2.95999925583601e-05
49 HashTable shuffled 2 list_all 0.00580970011651516
50 HashTable shuffled 3 insert 0.004507799865677953
51 HashTable shuffled 3 find 2.2900057956576347e-05
52 HashTable shuffled 3 delete 1.8700025975704193e-05
53 HashTable shuffled 3 list_all 0.003462200053036213
54 HashTable shuffled 4 insert 0.005082499934360385
55 HashTable shuffled 4 find 3.1800009310245514e-05
56 HashTable shuffled 4 delete 2.8799986466765404e-05
57 HashTable shuffled 4 list_all 0.007747200084850192
58 HashTable shuffled 5 insert 0.004538299981504679
59 HashTable shuffled 5 find 2.2900057956576347e-05
60 HashTable shuffled 5 delete 1.9300030544400215e-05
61 HashTable shuffled 5 list_all 0.003729799995198846
62 HashTable sorted 1 insert 0.005079899914562702
63 HashTable sorted 1 find 5.079992115497589e-05
64 HashTable sorted 1 delete 2.550007775425911e-05
65 HashTable sorted 1 list_all 0.005039500072598457
66 HashTable sorted 2 insert 0.004276499850675464
67 HashTable sorted 2 find 4.079984501004219e-05
68 HashTable sorted 2 delete 2.110004425048828e-05
69 HashTable sorted 2 list_all 0.004337100079283118
70 HashTable sorted 3 insert 0.006273699924349785
71 HashTable sorted 3 find 3.9400067180395126e-05
72 HashTable sorted 3 delete 1.919991336762905e-05
73 HashTable sorted 3 list_all 0.0032929000444710255
74 HashTable sorted 4 insert 0.004404899897053838
75 HashTable sorted 4 find 4.0499959141016006e-05
76 HashTable sorted 4 delete 2.0800158381462097e-05
77 HashTable sorted 4 list_all 0.006671200040727854
78 HashTable sorted 5 insert 0.00421059993095696
79 HashTable sorted 5 find 4.0999846532940865e-05
80 HashTable sorted 5 delete 2.140016295015812e-05
81 HashTable sorted 5 list_all 0.0034396001137793064
82 BST shuffled 1 insert 0.015235899947583675
83 BST shuffled 1 find 6.360001862049103e-05
84 BST shuffled 1 delete 9.159999899566174e-05
85 BST shuffled 1 list_all 0.0042282999493181705
86 BST shuffled 2 insert 0.016312200110405684
87 BST shuffled 2 find 5.859998054802418e-05
88 BST shuffled 2 delete 9.659980423748493e-05
89 BST shuffled 2 list_all 0.004191800020635128
90 BST shuffled 3 insert 0.015240099979564548
91 BST shuffled 3 find 5.859998054802418e-05
92 BST shuffled 3 delete 8.849985897541046e-05
93 BST shuffled 3 list_all 0.0036266997922211885
94 BST shuffled 4 insert 0.014052000129595399
95 BST shuffled 4 find 5.9300102293491364e-05
96 BST shuffled 4 delete 8.119991980493069e-05
97 BST shuffled 4 list_all 0.0027294999454170465
98 BST shuffled 5 insert 0.013222299981862307
99 BST shuffled 5 find 6.059999577701092e-05
100 BST shuffled 5 delete 7.970002479851246e-05
101 BST shuffled 5 list_all 0.0028162000235170126
102 BST sorted 1 insert 5.109697200125083
103 BST sorted 1 find 0.05814290000125766
104 BST sorted 1 delete 0.027696199947968125
105 BST sorted 1 list_all 0.004435899900272489
106 BST sorted 2 insert 6.02595020015724
107 BST sorted 2 find 0.05516729992814362
108 BST sorted 2 delete 0.028573499992489815
109 BST sorted 2 list_all 0.003455700119957328
110 BST sorted 3 insert 5.749598399968818
111 BST sorted 3 find 0.04719489999115467
112 BST sorted 3 delete 0.03186570014804602
113 BST sorted 3 list_all 0.002738000126555562
114 BST sorted 4 insert 5.19493699981831
115 BST sorted 4 find 0.052105900133028626
116 BST sorted 4 delete 0.028118600137531757
117 BST sorted 4 list_all 0.005104599986225367
118 BST sorted 5 insert 5.953492499887943
119 BST sorted 5 find 0.060425500152632594
120 BST sorted 5 delete 0.024722500005736947
121 BST sorted 5 list_all 0.004347699927166104

271
soldatkinao/lab1/task-1.py Normal file
View File

@ -0,0 +1,271 @@
# Task 1
import time
import random
import csv
from collections import defaultdict
def ll_insert(head, name, phone):
new = {'name': name, 'phone': phone, 'next': None}
if head is None:
return new
cur = head
while cur:
if cur['name'] == name:
cur['phone'] = phone
return head
if cur['next'] is None:
break
cur = cur['next']
cur['next'] = new
return head
def ll_find(head, name):
cur = head
while cur:
if cur['name'] == name:
return cur['phone']
cur = cur['next']
return None
def ll_delete(head, name):
if head is None:
return None
if head['name'] == name:
return head['next']
prev = head
cur = head['next']
while cur:
if cur['name'] == name:
prev['next'] = cur['next']
return head
prev = cur
cur = cur['next']
return head
def ll_list_all(head):
rec = []
cur = head
while cur:
rec.append((cur['name'], cur['phone']))
cur = cur['next']
rec.sort(key=lambda x: x[0])
return rec
# 2. Хеш-таблица
def ht_insert(buckets, name, phone):
idx = hash(name) % len(buckets)
buckets[idx] = ll_insert(buckets[idx], name, phone)
return buckets
def ht_find(buckets, name):
idx = hash(name) % len(buckets)
return ll_find(buckets[idx], name)
def ht_delete(buckets, name):
idx = hash(name) % len(buckets)
buckets[idx] = ll_delete(buckets[idx], name)
return buckets
def ht_list_all(buckets):
rec = []
for b in buckets:
cur = b
while cur:
rec.append((cur['name'], cur['phone']))
cur = cur['next']
rec.sort(key=lambda x: x[0])
return rec
def bst_insert(root, name, phone):
new = {'name': name, 'phone': phone, 'left': None, 'right': None}
if root is None:
return new
cur = root
while True:
if name < cur['name']:
if cur['left'] is None:
cur['left'] = new
break
cur = cur['left']
elif name > cur['name']:
if cur['right'] is None:
cur['right'] = new
break
cur = cur['right']
else:
cur['phone'] = phone
break
return root
def bst_find(root, name):
cur = root
while cur:
if name == cur['name']:
return cur['phone']
elif name < cur['name']:
cur = cur['left']
else:
cur = cur['right']
return None
def bst_delete(root, name):
if root is None:
return None
parent = None
cur = root
while cur and cur['name'] != name:
parent = cur
if name < cur['name']:
cur = cur['left']
else:
cur = cur['right']
if cur is None:
return root
# нет детей
if cur['left'] is None and cur['right'] is None:
if parent is None:
return None
if parent['left'] is cur:
parent['left'] = None
else:
parent['right'] = None
return root
# один ребёнок
if cur['left'] is None:
child = cur['right']
elif cur['right'] is None:
child = cur['left']
else:
# два ребёнка ищем минимальный в правом поддереве
succ_parent = cur
succ = cur['right']
while succ['left']:
succ_parent = succ
succ = succ['left']
cur['name'], cur['phone'] = succ['name'], succ['phone']
if succ_parent['left'] is succ:
succ_parent['left'] = succ['right']
else:
succ_parent['right'] = succ['right']
return root
if parent is None:
return child
if parent['left'] is cur:
parent['left'] = child
else:
parent['right'] = child
return root
def bst_list_all(root):
res = []
stack = []
cur = root
while stack or cur:
while cur:
stack.append(cur)
cur = cur['left']
cur = stack.pop()
res.append((cur['name'], cur['phone']))
cur = cur['right']
return res
def gen_data(N=10000):
data = []
for i in range(N):
name = f"user_{i:06d}"
phone = f"+7-{random.randint(100,999)}-{random.randint(100,999)}-{random.randint(1000,9999)}"
data.append((name, phone))
shuffled = data[:]
random.shuffle(shuffled)
sorted_data = sorted(data, key=lambda x: x[0])
return shuffled, sorted_data
# 5 повторений сохраняем все замеры
def run_test(init_func, ins_func, find_func, del_func, list_func,
shuffled, sorted_data, exist_names, missing_names, del_names):
rows = []
for order, dataset in [('shuffled', shuffled), ('sorted', sorted_data)]:
for rep in range(5):
s = init_func()
# вставка
t1 = time.perf_counter()
for name, phone in dataset:
s = ins_func(s, name, phone)
t2 = time.perf_counter()
rows.append([order, rep+1, 'insert', t2 - t1])
# поиск
t1 = time.perf_counter()
for name in exist_names:
find_func(s, name)
for name in missing_names:
find_func(s, name)
t2 = time.perf_counter()
rows.append([order, rep+1, 'find', t2 - t1])
# удаление
t1 = time.perf_counter()
for name in del_names:
s = del_func(s, name)
t2 = time.perf_counter()
rows.append([order, rep+1, 'delete', t2 - t1])
t1 = time.perf_counter()
list_func(s)
t2 = time.perf_counter()
rows.append([order, rep+1, 'list_all', t2 - t1])
return rows
if __name__ == '__main__':
N = 10000
print(f"Генерация {N} записей...")
shuffled, sorted_data = gen_data(N)
exist_names = [name for name, _ in shuffled[:100]]
missing_names = [f"none_{i}" for i in range(10)]
all_names = [name for name, _ in shuffled]
del_names = random.sample(all_names, 50)
all_rows = [] # для CSV
print("Связный список...")
rows = run_test(lambda: None, ll_insert, ll_find, ll_delete, ll_list_all,
shuffled, sorted_data, exist_names, missing_names, del_names)
for r in rows:
all_rows.append(['LinkedList'] + r)
print("Хеш-таблица...")
rows = run_test(lambda: [None]*2000, ht_insert, ht_find, ht_delete, ht_list_all,
shuffled, sorted_data, exist_names, missing_names, del_names)
for r in rows:
all_rows.append(['HashTable'] + r)
# бинарное дерево
print("Бинарное дерево...")
rows = run_test(lambda: None, bst_insert, bst_find, bst_delete, bst_list_all,
shuffled, sorted_data, exist_names, missing_names, del_names)
for r in rows:
all_rows.append(['BST'] + r)
# запись в CSV
with open('results.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Структура', 'Порядок', 'Повторение', 'Операция', 'Время (с)'])
writer.writerows(all_rows)
print("Все замеры сохранены в results.csv")
# Подсчёт и вывод средних
avg = defaultdict(list)
for row in all_rows:
struct, order, rep, op, t = row
avg[(struct, order, op)].append(t)
print("\nСредние значения (5 запусков):")
print(f"{'Структура':<12} {'Порядок':<10} {'Вставка':>10} {'Поиск':>10} {'Удаление':>10} {'ListAll':>10}")
for struct in ['LinkedList', 'HashTable', 'BST']:
for order in ['shuffled', 'sorted']:
row = [struct, order]
for op in ['insert', 'find', 'delete', 'list_all']:
vals = avg[(struct, order, op)]
avg_val = sum(vals)/len(vals)
row.append(f"{avg_val:.5f}")
print(f"{row[0]:<12} {row[1]:<10} {row[2]:>10} {row[3]:>10} {row[4]:>10} {row[5]:>10}")
print("\nГотово!!!!!.")

View File

@ -0,0 +1 @@
S E

View File

@ -0,0 +1,402 @@
import os
import time
import heapq
import csv
from collections import deque
from abc import ABC, abstractmethod
class Cell:
def __init__(self, x, y, wall=False):
self.x = x
self.y = y
self.wall = wall
self.start = False
self.exit = False
def prohodim(self):
return not self.wall
# лабиринт
class Maze:
def __init__(self, w, h):
self.w = w
self.h = h
self.grid = []
for i in range(h):
row = []
for j in range(w):
row.append(Cell(j, i))
self.grid.append(row)
self.start = None
self.exit = None
def get_cell(self, x, y):
if 0 <= x < self.w and 0 <= y < self.h:
return self.grid[y][x]
return None
def set_start(self, x, y):
c = self.get_cell(x, y)
if c:
c.start = True
self.start = (x, y)
def set_exit(self, x, y):
c = self.get_cell(x, y)
if c:
c.exit = True
self.exit = (x, y)
def neighbors(self, x, y):
res = []
for dx, dy in [(0,1),(1,0),(0,-1),(-1,0)]:
nx, ny = x+dx, y+dy
c = self.get_cell(nx, ny)
if c and c.prohodim():
res.append((nx, ny))
return res
class MazeBuilder(ABC):
@abstractmethod
def load(self, filename):
pass
class TextMazeBuilder(MazeBuilder):
def load(self, filename):
f = open(filename, 'r', encoding='utf-8')
lines = []
for line in f:
lines.append(line.rstrip('\n'))
f.close()
if not lines:
raise Exception("Файл пустой")
h = len(lines)
w = max([len(l) for l in lines])
maze = Maze(w, h)
for y in range(h):
line = lines[y]
for x in range(len(line)):
ch = line[x]
if ch == '#':
maze.grid[y][x] = Cell(x, y, wall=True)
elif ch == 'S':
maze.set_start(x, y)
elif ch == 'E':
maze.set_exit(x, y)
return maze
class Strategy(ABC):
@abstractmethod
def find_path(self, maze, start, end):
pass
# BFS
class BFS(Strategy):
def find_path(self, maze, start, end):
if start is None or end is None:
self.visited_count = 0
return None
q = deque()
q.append(start)
parent = {start: None}
while q:
cur = q.popleft()
if cur == end:
break
for nb in maze.neighbors(cur[0], cur[1]):
if nb not in parent:
parent[nb] = cur
q.append(nb)
self.visited_count = len(parent)
if end not in parent:
return None
path = []
c = end
while c is not None:
path.append(c)
c = parent[c]
path.reverse()
return path
# DFS
class DFS(Strategy):
def find_path(self, maze, start, end):
if start is None or end is None:
self.visited_count = 0
return None
stack = [start]
parent = {start: None}
while stack:
cur = stack.pop()
if cur == end:
break
for nb in maze.neighbors(cur[0], cur[1]):
if nb not in parent:
parent[nb] = cur
stack.append(nb)
self.visited_count = len(parent)
if end not in parent:
return None
path = []
c = end
while c is not None:
path.append(c)
c = parent[c]
path.reverse()
return path
# A*
class AStar(Strategy):
def heur(self, a, b):
return abs(a[0]-b[0]) + abs(a[1]-b[1])
def find_path(self, maze, start, end):
if start is None or end is None:
self.visited_count = 0
return None
heap = [(0, start)]
came_from = {}
g = {start: 0}
f = {start: self.heur(start, end)}
visited = set([start])
while heap:
cur = heapq.heappop(heap)[1]
visited.add(cur)
if cur == end:
break
for nb in maze.neighbors(cur[0], cur[1]):
newg = g[cur] + 1
if newg < g.get(nb, 999999):
came_from[nb] = cur
g[nb] = newg
f[nb] = newg + self.heur(nb, end)
heapq.heappush(heap, (f[nb], nb))
visited.add(nb)
self.visited_count = len(visited)
if end not in came_from and end != start:
return None
path = []
c = end
while c in came_from:
path.append(c)
c = came_from[c]
path.append(start)
path.reverse()
return path
# решение и статистика
class MazeSolver:
def __init__(self, maze, strategy):
self.maze = maze
self.strategy = strategy
def solve(self):
if self.maze.start is None or self.maze.exit is None:
return (0, 0, 0, False)
t0 = time.perf_counter()
path = self.strategy.find_path(self.maze, self.maze.start, self.maze.exit)
t = (time.perf_counter() - t0) * 1000
if path is None:
return (t, 0, 0, False)
return (t, self.strategy.visited_count, len(path), True)
# Наблюдатель
class Observer(ABC):
@abstractmethod
def update(self, event, data):
pass
class ConsoleView(Observer):
def __init__(self, maze):
self.maze = maze
self.player_pos = None
self.path_set = None
def update(self, event, data):
if event == 'init':
self.draw()
elif event == 'move':
self.player_pos = data
self.draw()
elif event == 'path':
self.path_set = set(data) if data else None
self.draw()
def clear(self):
os.system('cls' if os.name == 'nt' else 'clear')
def draw(self):
self.clear()
for y in range(self.maze.h):
row = ''
for x in range(self.maze.w):
cell = self.maze.get_cell(x, y)
if self.player_pos and (x,y) == self.player_pos:
row += 'P'
elif cell.start:
row += 'S'
elif cell.exit:
row += 'E'
elif cell.wall:
row += '#'
elif self.path_set and (x,y) in self.path_set:
row += '*'
else:
row += ' '
print(row)
print("WASD - ходить, F - BFS путь, G - A* путь, Z - отмена, Q - выход")
# игрок
class Player:
def __init__(self, maze):
self.maze = maze
self.pos = maze.start
self.history = []
def move(self, new_pos):
cell = self.maze.get_cell(new_pos[0], new_pos[1])
if cell and cell.prohodim():
self.history.append(self.pos)
self.pos = new_pos
return True
return False
def undo(self):
if self.history:
self.pos = self.history.pop()
return True
return False
class Command(ABC):
@abstractmethod
def execute(self):
pass
@abstractmethod
def undo(self):
pass
class MoveCommand(Command):
def __init__(self, player, dx, dy):
self.player = player
self.dx = dx
self.dy = dy
self.old = None
def execute(self):
self.old = self.player.pos
nx = self.player.pos[0] + self.dx
ny = self.player.pos[1] + self.dy
return self.player.move((nx, ny))
def undo(self):
if self.old:
return self.player.move(self.old)
return False
# эксперимент
def run_experiment(maze_files, repeats=5):
builder = TextMazeBuilder()
results = []
for fname in maze_files:
print("Обработка", fname)
maze = builder.load(fname)
if maze.start is None or maze.exit is None:
print(f"Предупреждение: в {fname} нет S или E, пропускаем")
continue
for algo_class, name in [(BFS, 'BFS'), (DFS, 'DFS'), (AStar, 'A*')]:
total_time = 0.0
total_visited = 0
path_len = 0
found = False
for _ in range(repeats):
alg = algo_class()
t0 = time.perf_counter()
path = alg.find_path(maze, maze.start, maze.exit)
t = (time.perf_counter() - t0) * 1000
total_time += t
total_visited += alg.visited_count
if path:
found = True
path_len = len(path)
results.append({
'maze': fname,
'algo': name,
'time': total_time / repeats,
'visited': total_visited / repeats,
'length': path_len,
'found': found
})
with open('results.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['maze','algo','time','visited','length','found'])
writer.writeheader()
writer.writerows(results)
print("\nРезультаты:")
for r in results:
print(f"{r['maze']:15} {r['algo']:5} время={r['time']:6.2f}ms посещено={r['visited']:6.1f} длина={r['length']}")
# режим игры
def play_game(maze):
view = ConsoleView(maze)
player = Player(maze)
view.update('init', None)
while True:
cmd = input("> ").strip().upper()
if cmd == 'W':
c = MoveCommand(player, 0, -1)
elif cmd == 'S':
c = MoveCommand(player, 0, 1)
elif cmd == 'A':
c = MoveCommand(player, -1, 0)
elif cmd == 'D':
c = MoveCommand(player, 1, 0)
elif cmd == 'F':
solver = MazeSolver(maze, BFS())
t, v, l, ok = solver.solve()
if ok:
path = BFS().find_path(maze, maze.start, maze.exit)
view.update('path', path)
print(f"BFS: длина={l} время={t:.2f}ms посещено={v}")
else:
print("Путь не найден")
continue
elif cmd == 'G':
astar = AStar()
path = astar.find_path(maze, maze.start, maze.exit)
if path:
view.update('path', path)
print(f"A*: длина={len(path)} посещено={astar.visited_count}")
else:
print("Путь не найден")
continue
elif cmd == 'Z':
if player.undo():
view.update('move', player.pos)
continue
elif cmd == 'Q':
break
else:
print("Неизвестная команда")
continue
if c.execute():
view.update('move', player.pos)
else:
print("Стена!")
def main():
print("1 - Игра\n2 - Эксперимент")
ch = input("> ")
builder = TextMazeBuilder()
if ch == '1':
maze = builder.load('small.txt') #легкая прогулка)
play_game(maze)
else:
files = ['small.txt', 'medium.txt', 'large.txt', 'empty.txt', 'no_exit.txt']
run_experiment(files)
if __name__ == '__main__':
main()
print ("\nЭто было долго, но вроде бы все готово. ") #можно конечно сделать многофайловую программу чтобы использовать классы как блоки длч строительства

100
soldatkinao/lab2/large.txt Normal file
View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 369 KiB

View File

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

Binary file not shown.

View File

@ -0,0 +1,16 @@
maze,algo,time,visited,length,found
small.txt,BFS,0.08549999911338091,65.0,15,True
small.txt,DFS,0.052140007028356194,65.0,31,True
small.txt,A*,0.08495999500155449,65.0,15,True
medium.txt,BFS,0.2455800073221326,254.0,95,True
medium.txt,DFS,0.21176000591367483,252.0,95,True
medium.txt,A*,0.23805999662727118,179.0,95,True
large.txt,BFS,0.8688000147230923,950.0,313,True
large.txt,DFS,0.9158599947113544,1079.0,467,True
large.txt,A*,1.1747399985324591,819.0,313,True
empty.txt,BFS,0.13876001466996968,102.0,102,True
empty.txt,DFS,0.10151999886147678,102.0,102,True
empty.txt,A*,0.13205999857746065,102.0,102,True
no_exit.txt,BFS,0.013979995856061578,12.0,0,False
no_exit.txt,DFS,0.012719997903332114,12.0,0,False
no_exit.txt,A*,0.01692000078037381,12.0,0,False
1 maze algo time visited length found
2 small.txt BFS 0.08549999911338091 65.0 15 True
3 small.txt DFS 0.052140007028356194 65.0 31 True
4 small.txt A* 0.08495999500155449 65.0 15 True
5 medium.txt BFS 0.2455800073221326 254.0 95 True
6 medium.txt DFS 0.21176000591367483 252.0 95 True
7 medium.txt A* 0.23805999662727118 179.0 95 True
8 large.txt BFS 0.8688000147230923 950.0 313 True
9 large.txt DFS 0.9158599947113544 1079.0 467 True
10 large.txt A* 1.1747399985324591 819.0 313 True
11 empty.txt BFS 0.13876001466996968 102.0 102 True
12 empty.txt DFS 0.10151999886147678 102.0 102 True
13 empty.txt A* 0.13205999857746065 102.0 102 True
14 no_exit.txt BFS 0.013979995856061578 12.0 0 False
15 no_exit.txt DFS 0.012719997903332114 12.0 0 False
16 no_exit.txt A* 0.01692000078037381 12.0 0 False

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 232 KiB