forked from UNN/2026-rff_mp
[1][2] Data Structures Lab and Lab for finding a way out of the maze
This commit is contained in:
parent
14272a7c25
commit
4950eb4f0d
252
SorokinAD/[1]lab_1/MP_BST.py
Normal file
252
SorokinAD/[1]lab_1/MP_BST.py
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
from MP_records import records
|
||||
import random as rd
|
||||
import time
|
||||
import csv
|
||||
import codecs
|
||||
import sys
|
||||
|
||||
sys.setrecursionlimit(15000)
|
||||
|
||||
|
||||
# ---------- Binary Search Tree ----------
|
||||
# Узел:
|
||||
# {
|
||||
# "name": name,
|
||||
# "phone": phone,
|
||||
# "left": None,
|
||||
# "right": None
|
||||
# }
|
||||
|
||||
|
||||
def bst_insert(root, name, phone):
|
||||
"""
|
||||
Вставляет новую запись или обновляет телефон по имени.
|
||||
Возвращает корень дерева.
|
||||
"""
|
||||
if root is None:
|
||||
return {
|
||||
"name": name,
|
||||
"phone": phone,
|
||||
"left": None,
|
||||
"right": None
|
||||
}
|
||||
|
||||
if name == root["name"]:
|
||||
root["phone"] = phone
|
||||
|
||||
elif name < root["name"]:
|
||||
root["left"] = bst_insert(root["left"], name, phone)
|
||||
|
||||
else:
|
||||
root["right"] = bst_insert(root["right"], name, phone)
|
||||
|
||||
return root
|
||||
|
||||
|
||||
def bst_find(root, name):
|
||||
"""
|
||||
Поиск телефона по имени.
|
||||
"""
|
||||
if root is None:
|
||||
return None
|
||||
|
||||
if name == root["name"]:
|
||||
return root["phone"]
|
||||
|
||||
if name < root["name"]:
|
||||
return bst_find(root["left"], name)
|
||||
|
||||
return bst_find(root["right"], name)
|
||||
|
||||
|
||||
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 name < root["name"]:
|
||||
root["left"] = bst_delete(root["left"], name)
|
||||
|
||||
elif name > root["name"]:
|
||||
root["right"] = bst_delete(root["right"], name)
|
||||
|
||||
else:
|
||||
# Узел без левого потомка
|
||||
if root["left"] is None:
|
||||
return root["right"]
|
||||
|
||||
# Узел без правого потомка
|
||||
if root["right"] is None:
|
||||
return root["left"]
|
||||
|
||||
# Узел с двумя потомками
|
||||
successor = bst_find_min(root["right"])
|
||||
|
||||
root["name"] = successor["name"]
|
||||
root["phone"] = successor["phone"]
|
||||
|
||||
root["right"] = bst_delete(root["right"], successor["name"])
|
||||
|
||||
return root
|
||||
|
||||
|
||||
def bst_inorder(root, result):
|
||||
"""
|
||||
Центрированный обход дерева.
|
||||
"""
|
||||
if root is None:
|
||||
return
|
||||
|
||||
bst_inorder(root["left"], result)
|
||||
|
||||
result.append((root["name"], root["phone"]))
|
||||
|
||||
bst_inorder(root["right"], result)
|
||||
|
||||
|
||||
def bst_list_all(root):
|
||||
"""
|
||||
Возвращает список записей в отсортированном порядке.
|
||||
"""
|
||||
result = []
|
||||
bst_inorder(root, result)
|
||||
return result
|
||||
|
||||
|
||||
# ---------- Benchmark helpers ----------
|
||||
|
||||
def build_bst(records_list):
|
||||
root = None
|
||||
|
||||
for name, phone in records_list:
|
||||
root = bst_insert(root, name, phone)
|
||||
|
||||
return root
|
||||
|
||||
|
||||
def measure_bst(records_list, mode_name, repeats=5):
|
||||
rows = []
|
||||
|
||||
insertion_times = []
|
||||
finding_times = []
|
||||
deletion_times = []
|
||||
|
||||
for run_number in range(1, repeats + 1):
|
||||
data = records_list[:]
|
||||
|
||||
if mode_name == "случайный":
|
||||
rd.shuffle(data)
|
||||
|
||||
# А. Вставка
|
||||
root = None
|
||||
|
||||
start = time.perf_counter()
|
||||
|
||||
for name, phone in data:
|
||||
root = bst_insert(root, name, phone)
|
||||
|
||||
end = time.perf_counter()
|
||||
|
||||
insertion_time = end - start
|
||||
insertion_times.append(insertion_time)
|
||||
|
||||
# Б. Поиск
|
||||
existing_names = [name for name, phone in rd.sample(data, 100)]
|
||||
missing_names = [f"None_{i}" for i in range(10)]
|
||||
|
||||
search_names = existing_names + missing_names
|
||||
rd.shuffle(search_names)
|
||||
|
||||
start = time.perf_counter()
|
||||
|
||||
for name in search_names:
|
||||
bst_find(root, name)
|
||||
|
||||
end = time.perf_counter()
|
||||
|
||||
finding_time = end - start
|
||||
finding_times.append(finding_time)
|
||||
|
||||
# В. Удаление
|
||||
delete_names = rd.sample(existing_names, 50)
|
||||
|
||||
start = time.perf_counter()
|
||||
|
||||
for name in delete_names:
|
||||
root = bst_delete(root, name)
|
||||
|
||||
end = time.perf_counter()
|
||||
|
||||
deletion_time = end - start
|
||||
deletion_times.append(deletion_time)
|
||||
|
||||
rows.append(["BinarySearchTree", mode_name, "вставка", run_number, insertion_time])
|
||||
rows.append(["BinarySearchTree", mode_name, "поиск", run_number, finding_time])
|
||||
rows.append(["BinarySearchTree", mode_name, "удаление", run_number, deletion_time])
|
||||
|
||||
rows.append(["BinarySearchTree", mode_name, "вставка", "среднее", sum(insertion_times) / repeats])
|
||||
rows.append(["BinarySearchTree", mode_name, "поиск", "среднее", sum(finding_times) / repeats])
|
||||
rows.append(["BinarySearchTree", mode_name, "удаление", "среднее", sum(deletion_times) / repeats])
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
def save_results(rows, filename="results.csv"):
|
||||
with codecs.open(filename, "a+", "utf-16") as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerows(rows)
|
||||
|
||||
|
||||
def run_shuffled(records_shuffled):
|
||||
rows = measure_bst(records_shuffled, "случайный")
|
||||
save_results(rows)
|
||||
return rows
|
||||
|
||||
|
||||
def run_sorted(records_sorted):
|
||||
rows = measure_bst(records_sorted, "отсортированный")
|
||||
save_results(rows)
|
||||
return rows
|
||||
|
||||
|
||||
# ---------- Manual tests ----------
|
||||
|
||||
def test():
|
||||
root = None
|
||||
|
||||
root = bst_insert(root, "Ivan", "111")
|
||||
root = bst_insert(root, "Anna", "222")
|
||||
root = bst_insert(root, "Petr", "333")
|
||||
root = bst_insert(root, "Maria", "444")
|
||||
|
||||
print(bst_find(root, "Anna")) # 222
|
||||
print(bst_find(root, "Unknown")) # None
|
||||
|
||||
root = bst_insert(root, "Anna", "999")
|
||||
print(bst_find(root, "Anna")) # 999
|
||||
|
||||
root = bst_delete(root, "Ivan")
|
||||
|
||||
print(bst_list_all(root))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
records_shuffled, records_sorted = records()
|
||||
|
||||
run_shuffled(records_shuffled)
|
||||
run_sorted(records_sorted)
|
||||
456
SorokinAD/[1]lab_1/MP_hash-table.py
Normal file
456
SorokinAD/[1]lab_1/MP_hash-table.py
Normal file
|
|
@ -0,0 +1,456 @@
|
|||
from MP_records import records
|
||||
import string
|
||||
import random as rd
|
||||
import time
|
||||
import csv
|
||||
import codecs
|
||||
|
||||
def polynomial_hash(word):
|
||||
p=11111
|
||||
m=(10**9)+9
|
||||
hashh=0
|
||||
for i in range(len(word)):
|
||||
hashh+=ord(word[i])*(p**i)
|
||||
hashh=hashh%m
|
||||
return hashh
|
||||
|
||||
def hash_to_index(hashh,length):
|
||||
#print(hashh)
|
||||
#if len(str(hashh))>4:
|
||||
#hashh=int(str(hashh)[3:])
|
||||
while hashh>length:
|
||||
hashh=hashh%(length)
|
||||
return hashh
|
||||
|
||||
def ll_insert(table,name,phone,index):
|
||||
if table[index]==None:
|
||||
entry={"name":name,"phone":phone,"next":None}
|
||||
table[index]=entry
|
||||
return table
|
||||
else:
|
||||
entry={"name":name,"phone":phone,"next":None}
|
||||
if table[index]["phone"]==phone:
|
||||
table[index]["name"]=name
|
||||
return table
|
||||
if table[index]["next"]==None:
|
||||
table[index]["next"]=entry
|
||||
return table
|
||||
else:
|
||||
nexxt=table[index]["next"]
|
||||
if nexxt["phone"]==phone:
|
||||
nexxt["name"]=name
|
||||
return table
|
||||
while nexxt["next"]!=None:
|
||||
nexxt=nexxt["next"]
|
||||
if nexxt["phone"]==phone:
|
||||
nexxt["name"]=name
|
||||
return table
|
||||
nexxt["next"]=entry
|
||||
return table
|
||||
|
||||
def ht_insert(table,name,phone):
|
||||
index=hash_to_index(polynomial_hash(name), len(table))
|
||||
ll_insert(table,name,phone,index)
|
||||
return table
|
||||
|
||||
def ht_find(table, name):
|
||||
index=hash_to_index(polynomial_hash(name), len(table))
|
||||
if table[index]!=None:
|
||||
if table[index]["name"]==name:
|
||||
return table[index]["phone"]
|
||||
elif table[index]["next"]!=None:
|
||||
if table[index]["next"]["name"]==name:
|
||||
return table[index]["next"]["phone"]
|
||||
else:
|
||||
nexxt=table[index]["next"]
|
||||
while nexxt["next"]!=None:
|
||||
nexxt=nexxt["next"]
|
||||
if nexxt["name"]==name:
|
||||
return nexxt["phone"]
|
||||
return None
|
||||
|
||||
def ht_delete(table,name):
|
||||
index=hash_to_index(polynomial_hash(name), len(table))
|
||||
if len(table)>0:
|
||||
if table[index]["name"]==name:
|
||||
if table[index]["next"]!=None:
|
||||
table[index]=table[index]["next"]
|
||||
return table
|
||||
else:
|
||||
table[index]=None
|
||||
return table
|
||||
elif table[index]["next"]!=None:
|
||||
if table[index]["next"]["name"]==name:
|
||||
if table[index]["next"]["next"]!=None:
|
||||
table[index]["next"]=table[index]["next"]["next"]
|
||||
return table
|
||||
else:
|
||||
table[index]["next"]=None
|
||||
return table
|
||||
elif table[index]["next"]["next"]!=None:
|
||||
nexxt1=table[index]["next"]
|
||||
nexxt2=nexxt1["next"]
|
||||
if nexxt2["name"]==name:
|
||||
if nexxt2["next"]!=None:
|
||||
nexxt1["next"]=nexxt2["next"]
|
||||
return table
|
||||
else:
|
||||
nexxt1["next"]=None
|
||||
return table
|
||||
while nexxt2["next"]!=None:
|
||||
nexxt1=nexxt2
|
||||
nexxt2=nexxt1["next"]
|
||||
if nexxt2["name"]==name:
|
||||
if nexxt2["next"]!=None:
|
||||
nexxt1["next"]=nexxt2["next"]
|
||||
return table
|
||||
else:
|
||||
nexxt1["next"]=None
|
||||
return table
|
||||
|
||||
def bad_sort(names,phones):
|
||||
names1=[]
|
||||
phones1=[]
|
||||
while len(names)>0:
|
||||
min_=names[0].encode()
|
||||
ph=phones[0]
|
||||
for i in range(len(names)):
|
||||
nm=names[i].encode()
|
||||
if nm<min_:
|
||||
min_=nm
|
||||
ph=phones[i]
|
||||
#print(min_.decode()," - ",ph)
|
||||
names1.append(min_.decode())
|
||||
phones1.append(ph)
|
||||
names.remove(min_.decode())
|
||||
phones.remove(ph)
|
||||
#print(names1,"\n",phones1)
|
||||
return names1, phones1
|
||||
|
||||
def Shell(names,phones):
|
||||
N = len(names)
|
||||
n = N // 2
|
||||
while n>0:
|
||||
for i in range (0,N-n):
|
||||
j=i
|
||||
while j+n<N:
|
||||
if (names[j].encode())>(names[j+n].encode()):
|
||||
t=names[j]
|
||||
t1=phones[j]
|
||||
names[j]=names[j+n]
|
||||
phones[j]=phones[j+n]
|
||||
names[j+n]=t
|
||||
phones[j+n]=t1
|
||||
j=i
|
||||
else:
|
||||
j+=n
|
||||
n=n//2
|
||||
return names,phones
|
||||
|
||||
def ht_listall(table):
|
||||
names=[]
|
||||
phones=[]
|
||||
pointer=0
|
||||
while pointer<len(table):
|
||||
if table[pointer]!=None:
|
||||
names.append(table[pointer]["name"])
|
||||
phones.append(table[pointer]["phone"])
|
||||
if table[pointer]["next"]!=None:
|
||||
names.append(table[pointer]["next"]["name"])
|
||||
phones.append(table[pointer]["next"]["phone"])
|
||||
nexxt=table[pointer]["next"]
|
||||
while nexxt["next"]!=None:
|
||||
nexxt=nexxt["next"]
|
||||
names.append(nexxt["name"])
|
||||
phones.append(nexxt["phone"])
|
||||
pointer+=1
|
||||
names1, phones1 = bad_sort(names, phones)
|
||||
#names1, phones1 = Shell(names, phones)
|
||||
for i in range(len(names1)):
|
||||
print(names1[i]," - ",phones1[i],end='')
|
||||
if i%4==0:
|
||||
print("\n")
|
||||
else:
|
||||
print(", ",end='')
|
||||
print("\n")
|
||||
|
||||
def test():
|
||||
table=[]
|
||||
for i in range(8):
|
||||
table.append(None)
|
||||
ht_insert(table, "Zyky", 1)
|
||||
ht_insert(table, "Abba", 2)
|
||||
ht_insert(table, "Babba", 3)
|
||||
ht_insert(table, "Aaaaa", 4)
|
||||
ht_insert(table, "Aakk", 5)
|
||||
ht_insert(table, "Bfaw", 6)
|
||||
ht_insert(table, "Uno", 7)
|
||||
ht_insert(table, "Uk", 8)
|
||||
ht_insert(table, "Uaa", 9)
|
||||
ht_insert(table, "h", 10)
|
||||
print(table)
|
||||
print(ht_find(table,"Aakk"))
|
||||
# ht_delete(table, "Aakk")
|
||||
#ht_delete(table, "Aaaaa")
|
||||
#print(table)
|
||||
#ht_delete(table, "Uaa")
|
||||
#ht_delete(table, "Zyky")
|
||||
print(table)
|
||||
ht_listall(table)
|
||||
|
||||
def run_shuffled(records_shuffled):
|
||||
insertion_times=[]
|
||||
finding_times=[]
|
||||
deletion_times1=[]
|
||||
print("Shuffled list: ")
|
||||
for k in range(5):
|
||||
lisst=[]
|
||||
for i in range(5000):
|
||||
lisst.append(None)
|
||||
rd.shuffle(records_shuffled)
|
||||
|
||||
#А. Вставка всех записей
|
||||
start=time.perf_counter()
|
||||
for i in range(len(records_shuffled)):
|
||||
ht_insert(lisst, records_shuffled[i][0], records_shuffled[i][1])
|
||||
end=time.perf_counter()
|
||||
insertion_times.append(end-start)
|
||||
|
||||
#Б. Поиск 100 случайных записей
|
||||
names=[]
|
||||
index=rd.randint(0,9899)
|
||||
for i in range(100):
|
||||
names.append(records_shuffled[index][0])
|
||||
index+=1
|
||||
for i in range(10):
|
||||
names.append("A")
|
||||
rd.shuffle(names)
|
||||
|
||||
start=time.perf_counter()
|
||||
for i in range(len(names)):
|
||||
ht_find(lisst,names[i])
|
||||
end=time.perf_counter()
|
||||
finding_times.append(end-start)
|
||||
|
||||
#В. Удаление 50 случайных записей
|
||||
for i in range(10):
|
||||
names.remove("A")
|
||||
rd.shuffle(names)
|
||||
deletion_times=[]
|
||||
|
||||
for i in range(50):
|
||||
start=time.perf_counter()
|
||||
ht_delete(lisst,names[i])
|
||||
end=time.perf_counter()
|
||||
ttt=end-start
|
||||
deletion_times.append(ttt)
|
||||
deletion_times1.append(deletion_times)
|
||||
|
||||
print("Run number ",k+1)
|
||||
print("Insertion time: ",insertion_times[k])
|
||||
print("Finding time: ",finding_times[k])
|
||||
print("Deletion times: ","\n",deletion_times)
|
||||
print("\n")
|
||||
|
||||
temp=0
|
||||
for i in range(5):
|
||||
temp+=insertion_times[i]
|
||||
temp=temp/5
|
||||
|
||||
results = [
|
||||
[u"Структура", u"Режим", u"Операция", u"Время (сек)"],
|
||||
["HashTable", u"случайный", u"вставка", insertion_times[0]],
|
||||
["HashTable", u"случайный", u"вставка", insertion_times[1]],
|
||||
["HashTable", u"случайный", u"вставка", insertion_times[2]],
|
||||
["HashTable", u"случайный", u"вставка", insertion_times[3]],
|
||||
["HashTable", u"случайный", u"вставка", insertion_times[4]],
|
||||
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
|
||||
["HashTable", u"случайный", u"вставка", temp,]
|
||||
]
|
||||
|
||||
with codecs.open("results.csv", "a+", "utf-16") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerows(results)
|
||||
writer.writerows("\n")
|
||||
|
||||
temp=0
|
||||
for i in range(5):
|
||||
temp+=finding_times[i]
|
||||
temp=temp/5
|
||||
|
||||
results = [
|
||||
[u"Структура", u"Режим", u"Операция", u"Время (сек)"],
|
||||
["HashTable", u"случайный", u"поиск", finding_times[0]],
|
||||
["HashTable", u"случайный", u"поиск", finding_times[1]],
|
||||
["HashTable", u"случайный", u"поиск", finding_times[2]],
|
||||
["HashTable", u"случайный", u"поиск", finding_times[3]],
|
||||
["HashTable", u"случайный", u"поиск", finding_times[4]],
|
||||
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
|
||||
["HashTable", u"случайный", u"поиск", temp,]
|
||||
]
|
||||
|
||||
with codecs.open("results.csv", "a+", "utf-16") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerows(results)
|
||||
writer.writerows("\n")
|
||||
|
||||
temp=0
|
||||
del_times=[]
|
||||
for i in range(5):
|
||||
for j in range(50):
|
||||
temp+=deletion_times1[i][j]
|
||||
temp=temp/50
|
||||
del_times.append(temp)
|
||||
temp=0
|
||||
|
||||
temp=0
|
||||
for i in range(5):
|
||||
temp+=del_times[i]
|
||||
temp=temp/5
|
||||
|
||||
results = [
|
||||
[u"Структура", u"Режим", u"Операция", u"Время (сек)"],
|
||||
["HashTable", u"случайный", u"удаление", del_times[0]],
|
||||
["HashTable", u"случайный", u"удаление", del_times[1]],
|
||||
["HashTable", u"случайный", u"удаление", del_times[2]],
|
||||
["HashTable", u"случайный", u"удаление", del_times[3]],
|
||||
["HashTable", u"случайный", u"удаление", del_times[4]],
|
||||
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
|
||||
["HashTable", u"случайный", u"удаление", temp,]
|
||||
]
|
||||
|
||||
with codecs.open("results.csv", "a+", "utf-16") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerows(results)
|
||||
writer.writerows("\n")
|
||||
writer.writerows("\n")
|
||||
|
||||
def run_sorted(records_shuffled):
|
||||
insertion_times=[]
|
||||
finding_times=[]
|
||||
deletion_times1=[]
|
||||
print("Sorted list: ")
|
||||
for k in range(5):
|
||||
lisst=[]
|
||||
for i in range(5000):
|
||||
lisst.append(None)
|
||||
|
||||
#А. Вставка всех записей
|
||||
start=time.perf_counter()
|
||||
for i in range(len(records_shuffled)):
|
||||
ht_insert(lisst, records_shuffled[i][0], records_shuffled[i][1])
|
||||
end=time.perf_counter()
|
||||
insertion_times.append(end-start)
|
||||
|
||||
#Б. Поиск 100 случайных записей
|
||||
names=[]
|
||||
index=rd.randint(0,9899)
|
||||
for i in range(100):
|
||||
names.append(records_shuffled[index][0])
|
||||
index+=1
|
||||
for i in range(10):
|
||||
names.append("A")
|
||||
rd.shuffle(names)
|
||||
|
||||
start=time.perf_counter()
|
||||
for i in range(len(names)):
|
||||
ht_find(lisst,names[i])
|
||||
end=time.perf_counter()
|
||||
finding_times.append(end-start)
|
||||
|
||||
#В. Удаление 50 случайных записей
|
||||
for i in range(10):
|
||||
names.remove("A")
|
||||
rd.shuffle(names)
|
||||
deletion_times=[]
|
||||
|
||||
for i in range(50):
|
||||
start=time.perf_counter()
|
||||
ht_delete(lisst,names[i])
|
||||
end=time.perf_counter()
|
||||
ttt=end-start
|
||||
deletion_times.append(ttt)
|
||||
deletion_times1.append(deletion_times)
|
||||
|
||||
print("Run number ",k+1)
|
||||
print("Insertion time: ",insertion_times[k])
|
||||
print("Finding time: ",finding_times[k])
|
||||
print("Deletion average:", sum(deletion_times))
|
||||
print("\n")
|
||||
|
||||
temp=0
|
||||
for i in range(5):
|
||||
temp+=insertion_times[i]
|
||||
temp=temp/5
|
||||
|
||||
results = [
|
||||
[u"Структура", u"Режим", u"Операция", u"Время (сек)"],
|
||||
["HashTable", u"отсортированный", u"вставка", insertion_times[0]],
|
||||
["HashTable", u"отсортированный", u"вставка", insertion_times[1]],
|
||||
["HashTable", u"отсортированный", u"вставка", insertion_times[2]],
|
||||
["HashTable", u"отсортированный", u"вставка", insertion_times[3]],
|
||||
["HashTable", u"сотсортированный", u"вставка", insertion_times[4]],
|
||||
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
|
||||
["HashTable", u"отсортированный", u"вставка", temp,]
|
||||
]
|
||||
|
||||
with codecs.open("results.csv", "a+", "utf-16") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerows(results)
|
||||
writer.writerows("\n")
|
||||
|
||||
temp=0
|
||||
for i in range(5):
|
||||
temp+=finding_times[i]
|
||||
temp=temp/5
|
||||
|
||||
results = [
|
||||
[u"Структура", u"Режим", u"Операция", u"Время (сек)"],
|
||||
["HashTable", u"отсортированный", u"поиск", finding_times[0]],
|
||||
["HashTable", u"отсортированный", u"поиск", finding_times[1]],
|
||||
["HashTable", u"отсортированный", u"поиск", finding_times[2]],
|
||||
["HashTable", u"отсортированный", u"поиск", finding_times[3]],
|
||||
["HashTable", u"отсортированный", u"поиск", finding_times[4]],
|
||||
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
|
||||
["HashTable", u"отсортированный", u"поиск", temp,]
|
||||
]
|
||||
|
||||
with codecs.open("results.csv", "a+", "utf-16") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerows(results)
|
||||
writer.writerows("\n")
|
||||
|
||||
temp=0
|
||||
del_times=[]
|
||||
for i in range(5):
|
||||
for j in range(50):
|
||||
temp+=deletion_times1[i][j]
|
||||
temp=temp/50
|
||||
del_times.append(temp)
|
||||
temp=0
|
||||
|
||||
temp=0
|
||||
for i in range(5):
|
||||
temp+=del_times[i]
|
||||
temp=temp/5
|
||||
|
||||
results = [
|
||||
[u"Структура", u"Режим", u"Операция", u"Время (сек)"],
|
||||
["HashTable", u"отсортированный", u"удаление", del_times[0]],
|
||||
["HashTable", u"отсортированный", u"удаление", del_times[1]],
|
||||
["HashTable", u"отсортированный", u"удаление", del_times[2]],
|
||||
["HashTable", u"отсортированный", u"удаление", del_times[3]],
|
||||
["HashTable", u"отсортированный", u"удаление", del_times[4]],
|
||||
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
|
||||
["HashTable", u"отсортированный", u"удаление", temp,]
|
||||
]
|
||||
|
||||
with codecs.open("results.csv", "a+", "utf-16") as f:
|
||||
writer = csv.writer(f)
|
||||
writer.writerows(results)
|
||||
writer.writerows("\n")
|
||||
writer.writerows("\n")
|
||||
|
||||
records_shuffled, records_sorted = records()
|
||||
run_shuffled(records_shuffled)
|
||||
run_sorted(records_sorted)
|
||||
241
SorokinAD/[1]lab_1/MP_linked_list.py
Normal file
241
SorokinAD/[1]lab_1/MP_linked_list.py
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
from MP_records import records
|
||||
import random as rd
|
||||
import time
|
||||
import csv
|
||||
import codecs
|
||||
|
||||
|
||||
# ---------- Linked List Phone Book ----------
|
||||
# Узел списка:
|
||||
# {"name": name, "phone": phone, "next": next_node}
|
||||
|
||||
|
||||
def ll_insert(head, name, phone):
|
||||
"""
|
||||
Добавляет новую запись или обновляет телефон по имени.
|
||||
Возвращает голову списка.
|
||||
"""
|
||||
new_node = {
|
||||
"name": name,
|
||||
"phone": phone,
|
||||
"next": None
|
||||
}
|
||||
|
||||
if head is None:
|
||||
return new_node
|
||||
|
||||
current = head
|
||||
|
||||
while True:
|
||||
if current["name"] == name:
|
||||
current["phone"] = phone
|
||||
return head
|
||||
|
||||
if current["next"] is None:
|
||||
break
|
||||
|
||||
current = current["next"]
|
||||
|
||||
current["next"] = new_node
|
||||
return head
|
||||
|
||||
|
||||
def ll_find(head, name):
|
||||
"""
|
||||
Ищет запись по имени.
|
||||
Возвращает телефон или None.
|
||||
"""
|
||||
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"]
|
||||
|
||||
previous = head
|
||||
current = head["next"]
|
||||
|
||||
while current is not None:
|
||||
if current["name"] == name:
|
||||
previous["next"] = current["next"]
|
||||
return head
|
||||
|
||||
previous = current
|
||||
current = current["next"]
|
||||
|
||||
return head
|
||||
|
||||
|
||||
def ll_list_all(head):
|
||||
"""
|
||||
Возвращает список всех записей, отсортированный по имени.
|
||||
"""
|
||||
result = []
|
||||
current = head
|
||||
|
||||
while current is not None:
|
||||
result.append((current["name"], current["phone"]))
|
||||
current = current["next"]
|
||||
|
||||
result.sort(key=lambda item: item[0])
|
||||
return result
|
||||
|
||||
|
||||
# ---------- Compatibility aliases ----------
|
||||
# Можно оставить старые имена, если они уже используются в отчете/других файлах.
|
||||
|
||||
def insert(head, name, phone):
|
||||
return ll_insert(head, name, phone)
|
||||
|
||||
|
||||
def find(head, name):
|
||||
return ll_find(head, name)
|
||||
|
||||
|
||||
def delete(head, name):
|
||||
return ll_delete(head, name)
|
||||
|
||||
|
||||
def list_all(head):
|
||||
return ll_list_all(head)
|
||||
|
||||
|
||||
# ---------- Benchmark helpers ----------
|
||||
|
||||
def build_linked_list(records_list):
|
||||
head = None
|
||||
|
||||
for name, phone in records_list:
|
||||
head = ll_insert(head, name, phone)
|
||||
|
||||
return head
|
||||
|
||||
|
||||
def measure_linked_list(records_list, mode_name, repeats=5):
|
||||
"""
|
||||
Выполняет 5 повторов:
|
||||
1. вставка всех записей;
|
||||
2. поиск 100 существующих и 10 отсутствующих имен;
|
||||
3. удаление 50 существующих имен.
|
||||
|
||||
Возвращает строки для записи в CSV.
|
||||
"""
|
||||
rows = []
|
||||
|
||||
insertion_times = []
|
||||
finding_times = []
|
||||
deletion_times = []
|
||||
|
||||
for run_number in range(1, repeats + 1):
|
||||
data = records_list[:]
|
||||
|
||||
if mode_name == "случайный":
|
||||
rd.shuffle(data)
|
||||
|
||||
# А. Вставка всех записей
|
||||
head = None
|
||||
start = time.perf_counter()
|
||||
|
||||
for name, phone in data:
|
||||
head = ll_insert(head, name, phone)
|
||||
|
||||
end = time.perf_counter()
|
||||
insertion_time = end - start
|
||||
insertion_times.append(insertion_time)
|
||||
|
||||
# Б. Поиск 100 существующих + 10 отсутствующих
|
||||
existing_names = [name for name, phone in rd.sample(data, 100)]
|
||||
missing_names = [f"None_{i}" for i in range(10)]
|
||||
search_names = existing_names + missing_names
|
||||
rd.shuffle(search_names)
|
||||
|
||||
start = time.perf_counter()
|
||||
|
||||
for name in search_names:
|
||||
ll_find(head, name)
|
||||
|
||||
end = time.perf_counter()
|
||||
finding_time = end - start
|
||||
finding_times.append(finding_time)
|
||||
|
||||
# В. Удаление 50 существующих
|
||||
delete_names = rd.sample(existing_names, 50)
|
||||
|
||||
start = time.perf_counter()
|
||||
|
||||
for name in delete_names:
|
||||
head = ll_delete(head, name)
|
||||
|
||||
end = time.perf_counter()
|
||||
deletion_time = end - start
|
||||
deletion_times.append(deletion_time)
|
||||
|
||||
rows.append(["LinkedList", mode_name, "вставка", run_number, insertion_time])
|
||||
rows.append(["LinkedList", mode_name, "поиск", run_number, finding_time])
|
||||
rows.append(["LinkedList", mode_name, "удаление", run_number, deletion_time])
|
||||
|
||||
rows.append(["LinkedList", mode_name, "вставка", "среднее", sum(insertion_times) / repeats])
|
||||
rows.append(["LinkedList", mode_name, "поиск", "среднее", sum(finding_times) / repeats])
|
||||
rows.append(["LinkedList", mode_name, "удаление", "среднее", sum(deletion_times) / repeats])
|
||||
|
||||
return rows
|
||||
|
||||
|
||||
def save_results(rows, filename="results.csv"):
|
||||
with codecs.open(filename, "a+", "utf-16") as file:
|
||||
writer = csv.writer(file)
|
||||
writer.writerows(rows)
|
||||
|
||||
|
||||
def run_shuffled(records_shuffled):
|
||||
rows = measure_linked_list(records_shuffled, "случайный")
|
||||
save_results(rows)
|
||||
return rows
|
||||
|
||||
|
||||
def run_sorted(records_sorted):
|
||||
rows = measure_linked_list(records_sorted, "отсортированный")
|
||||
save_results(rows)
|
||||
return rows
|
||||
|
||||
|
||||
# ---------- Manual tests ----------
|
||||
|
||||
def test():
|
||||
head = None
|
||||
|
||||
head = ll_insert(head, "Ivan", "111")
|
||||
head = ll_insert(head, "Anna", "222")
|
||||
head = ll_insert(head, "Petr", "333")
|
||||
|
||||
print(ll_find(head, "Anna")) # 222
|
||||
print(ll_find(head, "Unknown")) # None
|
||||
|
||||
head = ll_insert(head, "Anna", "999")
|
||||
print(ll_find(head, "Anna")) # 999
|
||||
|
||||
head = ll_delete(head, "Ivan")
|
||||
print(ll_list_all(head)) # [('Anna', '999'), ('Petr', '333')]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
records_shuffled, records_sorted = records()
|
||||
|
||||
run_shuffled(records_shuffled)
|
||||
run_sorted(records_sorted)
|
||||
34
SorokinAD/[1]lab_1/MP_names.py
Normal file
34
SorokinAD/[1]lab_1/MP_names.py
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
import random
|
||||
VOWELS = "aeiou"
|
||||
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
|
||||
def generate_name():
|
||||
length = random.randint(4, 10)
|
||||
|
||||
name = ""
|
||||
|
||||
for i in range(length):
|
||||
if i % 2 == 0:
|
||||
name += random.choice(CONSONANTS)
|
||||
else:
|
||||
name += random.choice(VOWELS)
|
||||
|
||||
return name.capitalize()
|
||||
|
||||
|
||||
def generate_unique_names(count):
|
||||
names = set()
|
||||
|
||||
while len(names) < count:
|
||||
names.add(generate_name())
|
||||
|
||||
return list(names)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
names = generate_unique_names(5000)
|
||||
|
||||
with open("names.txt", "w", encoding="utf-8") as file:
|
||||
for name in names:
|
||||
file.write(name + "\n")
|
||||
|
||||
print("names.txt generated")
|
||||
73
SorokinAD/[1]lab_1/MP_records.py
Normal file
73
SorokinAD/[1]lab_1/MP_records.py
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import random as rd
|
||||
|
||||
def Shell(arr):
|
||||
N = len(arr)
|
||||
n = N // 2
|
||||
while n>0:
|
||||
for i in range (0,N-n):
|
||||
j=i
|
||||
while j+n<N:
|
||||
if arr[j]>arr[j+n]:
|
||||
t=arr[j]
|
||||
arr[j]=arr[j+n]
|
||||
arr[j+n]=t
|
||||
j=i
|
||||
else:
|
||||
j+=n
|
||||
n=n//2
|
||||
return arr
|
||||
|
||||
def records():
|
||||
phones=[]
|
||||
first=0
|
||||
second=0
|
||||
third=0
|
||||
fourth=0
|
||||
for i in range(10000):
|
||||
phones.append(str(first)+str(second)+str(third)+str(fourth))
|
||||
fourth+=1
|
||||
if fourth==10:
|
||||
third+=1
|
||||
fourth=0
|
||||
if third==10:
|
||||
second+=1
|
||||
third=0
|
||||
if second==10:
|
||||
first+=1
|
||||
second=0
|
||||
phones2=phones.copy()
|
||||
|
||||
f=open("names.txt","r")
|
||||
count=0
|
||||
names=[]
|
||||
while count<5000:
|
||||
name=f.readline()
|
||||
names.append(name[:len(name)-1])
|
||||
names.append(name[:len(name)-1])
|
||||
count+=1
|
||||
f.close()
|
||||
|
||||
names_sorted=names.copy()
|
||||
for i in range(10000):
|
||||
names_sorted[i]=names_sorted[i].encode()
|
||||
Shell(names_sorted)
|
||||
for i in range(10000):
|
||||
names_sorted[i]=names_sorted[i].decode()
|
||||
|
||||
records_shuffled=[]
|
||||
records_sorted=[]
|
||||
count=0
|
||||
while count<10000:
|
||||
name_var=rd.randint(0,len(names)-1)
|
||||
phone_var=rd.randint(0,len(phones2)-1)
|
||||
records_shuffled.append((names[name_var],phones[count]))
|
||||
records_sorted.append((names_sorted[count],phones2[phone_var]))
|
||||
names.remove(names[name_var])
|
||||
phones2.remove(phones2[phone_var])
|
||||
count+=1
|
||||
|
||||
rd.shuffle(records_shuffled)
|
||||
return records_shuffled, records_sorted
|
||||
#print(records_shuffled)
|
||||
#print(records_sorted)
|
||||
|
||||
BIN
SorokinAD/[1]lab_1/graphs_lab.xlsx
Normal file
BIN
SorokinAD/[1]lab_1/graphs_lab.xlsx
Normal file
Binary file not shown.
5000
SorokinAD/[1]lab_1/names.txt
Normal file
5000
SorokinAD/[1]lab_1/names.txt
Normal file
File diff suppressed because it is too large
Load Diff
BIN
SorokinAD/[1]lab_1/report.docx
Normal file
BIN
SorokinAD/[1]lab_1/report.docx
Normal file
Binary file not shown.
BIN
SorokinAD/[1]lab_1/results.csv
Normal file
BIN
SorokinAD/[1]lab_1/results.csv
Normal file
Binary file not shown.
|
Can't render this file because it has a wrong number of fields in line 37.
|
143
SorokinAD/[2]lab_2/benchmark.py
Normal file
143
SorokinAD/[2]lab_2/benchmark.py
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
import csv
|
||||
import os
|
||||
|
||||
from builders import TextFileMazeBuilder
|
||||
|
||||
from solver import MazeSolver
|
||||
|
||||
from strategies import (
|
||||
BFSStrategy,
|
||||
DFSStrategy,
|
||||
AStarStrategy
|
||||
)
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Benchmark
|
||||
# =========================================================
|
||||
|
||||
class BenchmarkRunner:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.strategies = [
|
||||
("BFS", BFSStrategy()),
|
||||
("DFS", DFSStrategy()),
|
||||
("A*", AStarStrategy()),
|
||||
]
|
||||
|
||||
# =====================================================
|
||||
# Run benchmark
|
||||
# =====================================================
|
||||
|
||||
def run(
|
||||
self,
|
||||
maze_files: list[str],
|
||||
runs_per_test: int = 5
|
||||
):
|
||||
|
||||
results = []
|
||||
|
||||
builder = TextFileMazeBuilder()
|
||||
|
||||
for maze_file in maze_files:
|
||||
|
||||
print()
|
||||
print(f"Testing: {maze_file}")
|
||||
|
||||
maze = builder.build_from_file(
|
||||
maze_file
|
||||
)
|
||||
|
||||
for strategy_name, strategy in self.strategies:
|
||||
|
||||
total_time = 0
|
||||
total_visited = 0
|
||||
total_path_length = 0
|
||||
|
||||
for _ in range(runs_per_test):
|
||||
|
||||
solver = MazeSolver(
|
||||
maze,
|
||||
strategy
|
||||
)
|
||||
|
||||
path, stats = solver.solve()
|
||||
|
||||
total_time += stats.time_ms
|
||||
total_visited += stats.visited_cells
|
||||
total_path_length += stats.path_length
|
||||
|
||||
avg_time = (
|
||||
total_time / runs_per_test
|
||||
)
|
||||
|
||||
avg_visited = (
|
||||
total_visited / runs_per_test
|
||||
)
|
||||
|
||||
avg_path_length = (
|
||||
total_path_length / runs_per_test
|
||||
)
|
||||
|
||||
result = {
|
||||
"maze": maze_file,
|
||||
"strategy": strategy_name,
|
||||
"time_ms": round(avg_time, 3),
|
||||
"visited_cells": int(avg_visited),
|
||||
"path_length": int(avg_path_length),
|
||||
}
|
||||
|
||||
results.append(result)
|
||||
|
||||
print(
|
||||
f"{strategy_name}: "
|
||||
f"time={avg_time:.3f} ms, "
|
||||
f"visited={avg_visited:.0f}, "
|
||||
f"path={avg_path_length:.0f}"
|
||||
)
|
||||
|
||||
self.save_to_csv(results)
|
||||
|
||||
# =====================================================
|
||||
# Save CSV
|
||||
# =====================================================
|
||||
|
||||
@staticmethod
|
||||
def save_to_csv(results):
|
||||
|
||||
base_dir = os.path.dirname(__file__)
|
||||
|
||||
csv_path = os.path.join(
|
||||
base_dir,
|
||||
"benchmark_results.csv"
|
||||
)
|
||||
|
||||
with open(
|
||||
csv_path,
|
||||
"w",
|
||||
newline="",
|
||||
encoding="utf-8"
|
||||
) as file:
|
||||
|
||||
writer = csv.DictWriter(
|
||||
file,
|
||||
fieldnames=[
|
||||
"maze",
|
||||
"strategy",
|
||||
"time_ms",
|
||||
"visited_cells",
|
||||
"path_length"
|
||||
]
|
||||
)
|
||||
|
||||
writer.writeheader()
|
||||
|
||||
for row in results:
|
||||
|
||||
writer.writerow(row)
|
||||
|
||||
print()
|
||||
print(
|
||||
f"Results saved to: {csv_path}"
|
||||
)
|
||||
13
SorokinAD/[2]lab_2/benchmark_results.csv
Normal file
13
SorokinAD/[2]lab_2/benchmark_results.csv
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
maze,strategy,time_ms,visited_cells,path_length
|
||||
mazes/small.txt,BFS,0.034,17,12
|
||||
mazes/small.txt,DFS,0.026,13,12
|
||||
mazes/small.txt,A*,0.048,17,12
|
||||
mazes/open.txt,BFS,0.219,100,19
|
||||
mazes/open.txt,DFS,0.135,55,55
|
||||
mazes/open.txt,A*,0.334,100,19
|
||||
mazes/medium.txt,BFS,0.093,36,0
|
||||
mazes/medium.txt,DFS,0.059,36,0
|
||||
mazes/medium.txt,A*,0.087,36,0
|
||||
mazes/no_exit.txt,BFS,0.008,5,0
|
||||
mazes/no_exit.txt,DFS,0.007,5,0
|
||||
mazes/no_exit.txt,A*,0.011,5,0
|
||||
|
60
SorokinAD/[2]lab_2/builders.py
Normal file
60
SorokinAD/[2]lab_2/builders.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
from abc import ABC, abstractmethod
|
||||
|
||||
from cell import Cell
|
||||
from maze import Maze
|
||||
|
||||
|
||||
class MazeBuilder(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def build_from_file(self, filename: str) -> Maze:
|
||||
pass
|
||||
|
||||
|
||||
class TextFileMazeBuilder(MazeBuilder):
|
||||
|
||||
def build_from_file(self, filename: str) -> Maze:
|
||||
|
||||
with open(filename, "r", encoding="utf-8") as file:
|
||||
lines = [line.rstrip("\n") for line in file]
|
||||
|
||||
cells = []
|
||||
|
||||
start = None
|
||||
exit = None
|
||||
|
||||
for y, line in enumerate(lines):
|
||||
|
||||
row = []
|
||||
|
||||
for x, char in enumerate(line):
|
||||
|
||||
is_wall = char == "#"
|
||||
is_start = char == "S"
|
||||
is_exit = char == "E"
|
||||
|
||||
cell = Cell(
|
||||
x=x,
|
||||
y=y,
|
||||
is_wall=is_wall,
|
||||
is_start=is_start,
|
||||
is_exit=is_exit
|
||||
)
|
||||
|
||||
if is_start:
|
||||
start = cell
|
||||
|
||||
if is_exit:
|
||||
exit = cell
|
||||
|
||||
row.append(cell)
|
||||
|
||||
cells.append(row)
|
||||
|
||||
if start is None:
|
||||
raise ValueError("Старт S не найден")
|
||||
|
||||
if exit is None:
|
||||
raise ValueError("Выход E не найден")
|
||||
|
||||
return Maze(cells, start, exit)
|
||||
13
SorokinAD/[2]lab_2/cell.py
Normal file
13
SorokinAD/[2]lab_2/cell.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
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
|
||||
91
SorokinAD/[2]lab_2/commands.py
Normal file
91
SorokinAD/[2]lab_2/commands.py
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
from abc import ABC, abstractmethod
|
||||
|
||||
from cell import Cell
|
||||
from maze import Maze
|
||||
|
||||
|
||||
class Player:
|
||||
|
||||
def __init__(self, start_cell: Cell):
|
||||
|
||||
self.current_cell = start_cell
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Command
|
||||
# =========================================================
|
||||
|
||||
class Command(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def execute(self):
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def undo(self):
|
||||
pass
|
||||
|
||||
|
||||
# =========================================================
|
||||
# MoveCommand
|
||||
# =========================================================
|
||||
|
||||
class MoveCommand(Command):
|
||||
|
||||
DIRECTIONS = {
|
||||
"W": (0, -1),
|
||||
"S": (0, 1),
|
||||
"A": (-1, 0),
|
||||
"D": (1, 0),
|
||||
}
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
player: Player,
|
||||
maze: Maze,
|
||||
direction: str
|
||||
):
|
||||
|
||||
self.player = player
|
||||
self.maze = maze
|
||||
self.direction = direction.upper()
|
||||
|
||||
self.previous_cell = None
|
||||
|
||||
def execute(self):
|
||||
|
||||
if self.direction not in self.DIRECTIONS:
|
||||
return False
|
||||
|
||||
dx, dy = self.DIRECTIONS[self.direction]
|
||||
|
||||
current = self.player.current_cell
|
||||
|
||||
new_x = current.x + dx
|
||||
new_y = current.y + dy
|
||||
|
||||
target = self.maze.get_cell(
|
||||
new_x,
|
||||
new_y
|
||||
)
|
||||
|
||||
if target is None:
|
||||
return False
|
||||
|
||||
if not target.is_passable():
|
||||
return False
|
||||
|
||||
self.previous_cell = current
|
||||
|
||||
self.player.current_cell = target
|
||||
|
||||
return True
|
||||
|
||||
def undo(self):
|
||||
|
||||
if self.previous_cell is not None:
|
||||
|
||||
self.player.current_cell = (
|
||||
self.previous_cell
|
||||
)
|
||||
|
||||
164
SorokinAD/[2]lab_2/main.py
Normal file
164
SorokinAD/[2]lab_2/main.py
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
from builders import TextFileMazeBuilder
|
||||
|
||||
from strategies import (
|
||||
BFSStrategy,
|
||||
DFSStrategy,
|
||||
AStarStrategy
|
||||
)
|
||||
|
||||
from solver import MazeSolver
|
||||
|
||||
from visualization import ConsoleView
|
||||
|
||||
from commands import (
|
||||
Player,
|
||||
MoveCommand
|
||||
)
|
||||
|
||||
|
||||
def test_strategy(name, strategy, maze):
|
||||
|
||||
print()
|
||||
print("=" * 40)
|
||||
|
||||
view = ConsoleView()
|
||||
|
||||
solver = MazeSolver(
|
||||
maze,
|
||||
strategy
|
||||
)
|
||||
|
||||
solver.add_observer(view)
|
||||
|
||||
path, stats = solver.solve()
|
||||
|
||||
print()
|
||||
print(f"Strategy: {name}")
|
||||
|
||||
print(
|
||||
f"Time: {stats.time_ms:.3f} ms"
|
||||
)
|
||||
|
||||
print(
|
||||
f"Visited cells: {stats.visited_cells}"
|
||||
)
|
||||
|
||||
print(
|
||||
f"Path length: {stats.path_length}"
|
||||
)
|
||||
|
||||
print()
|
||||
|
||||
view.render(
|
||||
maze,
|
||||
path
|
||||
)
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Manual mode
|
||||
# =========================================================
|
||||
|
||||
def manual_mode(maze):
|
||||
|
||||
print()
|
||||
print("=" * 40)
|
||||
print("MANUAL MODE")
|
||||
print("W/A/S/D - move")
|
||||
print("U - undo")
|
||||
print("Q - quit")
|
||||
|
||||
view = ConsoleView()
|
||||
|
||||
player = Player(
|
||||
maze.start
|
||||
)
|
||||
|
||||
history = []
|
||||
|
||||
while True:
|
||||
|
||||
print()
|
||||
|
||||
view.render(
|
||||
maze,
|
||||
current=player.current_cell
|
||||
)
|
||||
|
||||
if player.current_cell == maze.exit:
|
||||
|
||||
print()
|
||||
print("YOU WIN!")
|
||||
|
||||
break
|
||||
|
||||
command_input = input(
|
||||
"\nCommand: "
|
||||
).upper()
|
||||
|
||||
if command_input == "Q":
|
||||
break
|
||||
|
||||
if command_input == "U":
|
||||
|
||||
if history:
|
||||
|
||||
last_command = history.pop()
|
||||
|
||||
last_command.undo()
|
||||
|
||||
continue
|
||||
|
||||
command = MoveCommand(
|
||||
player,
|
||||
maze,
|
||||
command_input
|
||||
)
|
||||
|
||||
success = command.execute()
|
||||
|
||||
if success:
|
||||
history.append(command)
|
||||
else:
|
||||
print("Invalid move")
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
builder = TextFileMazeBuilder()
|
||||
|
||||
maze = builder.build_from_file(
|
||||
"mazes/small.txt"
|
||||
)
|
||||
|
||||
# =====================================
|
||||
# Strategies
|
||||
# =====================================
|
||||
|
||||
test_strategy(
|
||||
"BFS",
|
||||
BFSStrategy(),
|
||||
maze
|
||||
)
|
||||
|
||||
test_strategy(
|
||||
"DFS",
|
||||
DFSStrategy(),
|
||||
maze
|
||||
)
|
||||
|
||||
test_strategy(
|
||||
"A*",
|
||||
AStarStrategy(),
|
||||
maze
|
||||
)
|
||||
|
||||
# =====================================
|
||||
# Manual mode
|
||||
# =====================================
|
||||
|
||||
manual_mode(maze)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
33
SorokinAD/[2]lab_2/maze.py
Normal file
33
SorokinAD/[2]lab_2/maze.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
from cell import Cell
|
||||
|
||||
|
||||
class Maze:
|
||||
def __init__(self, cells: list[list[Cell]], start: Cell, exit: Cell):
|
||||
self.cells = cells
|
||||
self.height = len(cells)
|
||||
self.width = len(cells[0]) if self.height > 0 else 0
|
||||
self.start = start
|
||||
self.exit = exit
|
||||
|
||||
def get_cell(self, x: int, y: int) -> Cell | None:
|
||||
if 0 <= y < self.height and 0 <= x < self.width:
|
||||
return self.cells[y][x]
|
||||
return None
|
||||
|
||||
def get_neighbors(self, cell: Cell) -> list[Cell]:
|
||||
directions = [
|
||||
(0, -1),
|
||||
(0, 1),
|
||||
(-1, 0),
|
||||
(1, 0),
|
||||
]
|
||||
|
||||
neighbors = []
|
||||
|
||||
for dx, dy in directions:
|
||||
neighbor = self.get_cell(cell.x + dx, cell.y + dy)
|
||||
|
||||
if neighbor is not None and neighbor.is_passable():
|
||||
neighbors.append(neighbor)
|
||||
|
||||
return neighbors
|
||||
11
SorokinAD/[2]lab_2/mazes/medium.txt
Normal file
11
SorokinAD/[2]lab_2/mazes/medium.txt
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
####################
|
||||
#S # # #
|
||||
### ### ##### ### ##
|
||||
# # # ##
|
||||
# ### ### # ##### ##
|
||||
# # # # # #
|
||||
# # ##### ##### # #
|
||||
# # # # # #
|
||||
# ##### ##### # # #
|
||||
# # # E#
|
||||
####################
|
||||
5
SorokinAD/[2]lab_2/mazes/no_exit.txt
Normal file
5
SorokinAD/[2]lab_2/mazes/no_exit.txt
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
##########
|
||||
#S# #E#
|
||||
# ### ####
|
||||
# # #
|
||||
##########
|
||||
10
SorokinAD/[2]lab_2/mazes/open.txt
Normal file
10
SorokinAD/[2]lab_2/mazes/open.txt
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
S
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
E
|
||||
5
SorokinAD/[2]lab_2/mazes/small.txt
Normal file
5
SorokinAD/[2]lab_2/mazes/small.txt
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
##########
|
||||
#S #E#
|
||||
# ### ## #
|
||||
# # #
|
||||
##########
|
||||
BIN
SorokinAD/[2]lab_2/otchet.docx
Normal file
BIN
SorokinAD/[2]lab_2/otchet.docx
Normal file
Binary file not shown.
20
SorokinAD/[2]lab_2/run_benchmark.py
Normal file
20
SorokinAD/[2]lab_2/run_benchmark.py
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
from benchmark import BenchmarkRunner
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
benchmark = BenchmarkRunner()
|
||||
|
||||
benchmark.run(
|
||||
maze_files=[
|
||||
"mazes/small.txt",
|
||||
"mazes/open.txt",
|
||||
"mazes/medium.txt",
|
||||
"mazes/no_exit.txt",
|
||||
],
|
||||
runs_per_test=10
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
86
SorokinAD/[2]lab_2/solver.py
Normal file
86
SorokinAD/[2]lab_2/solver.py
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
import time
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from maze import Maze
|
||||
from strategies import PathFindingStrategy
|
||||
|
||||
|
||||
@dataclass
|
||||
class SearchStats:
|
||||
time_ms: float
|
||||
visited_cells: int
|
||||
path_length: int
|
||||
|
||||
|
||||
class MazeSolver:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
maze: Maze,
|
||||
strategy: PathFindingStrategy
|
||||
):
|
||||
|
||||
self.maze = maze
|
||||
self.strategy = strategy
|
||||
|
||||
self.observers = []
|
||||
|
||||
# =====================================
|
||||
# Observer
|
||||
# =====================================
|
||||
|
||||
def add_observer(self, observer):
|
||||
|
||||
self.observers.append(observer)
|
||||
|
||||
def notify(self, event: str):
|
||||
|
||||
for observer in self.observers:
|
||||
observer.update(event)
|
||||
|
||||
# =====================================
|
||||
# Strategy
|
||||
# =====================================
|
||||
|
||||
def set_strategy(
|
||||
self,
|
||||
strategy: PathFindingStrategy
|
||||
):
|
||||
|
||||
self.strategy = strategy
|
||||
|
||||
self.notify(
|
||||
f"Strategy changed to {strategy.__class__.__name__}"
|
||||
)
|
||||
|
||||
# =====================================
|
||||
# Solve
|
||||
# =====================================
|
||||
|
||||
def solve(self):
|
||||
|
||||
self.notify("Search started")
|
||||
|
||||
start_time = time.perf_counter()
|
||||
|
||||
path, visited_cells = self.strategy.find_path(
|
||||
self.maze,
|
||||
self.maze.start,
|
||||
self.maze.exit
|
||||
)
|
||||
|
||||
end_time = time.perf_counter()
|
||||
|
||||
stats = SearchStats(
|
||||
time_ms=(end_time - start_time) * 1000,
|
||||
visited_cells=visited_cells,
|
||||
path_length=len(path)
|
||||
)
|
||||
|
||||
if path:
|
||||
self.notify("Path found")
|
||||
else:
|
||||
self.notify("No path found")
|
||||
|
||||
return path, stats
|
||||
218
SorokinAD/[2]lab_2/strategies.py
Normal file
218
SorokinAD/[2]lab_2/strategies.py
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
from abc import ABC, abstractmethod
|
||||
from collections import deque
|
||||
from heapq import heappush, heappop
|
||||
|
||||
from maze import Maze
|
||||
from cell import Cell
|
||||
|
||||
|
||||
class PathFindingStrategy(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def find_path(
|
||||
self,
|
||||
maze: Maze,
|
||||
start: Cell,
|
||||
exit: Cell
|
||||
) -> tuple[list[Cell], int]:
|
||||
|
||||
pass
|
||||
|
||||
|
||||
# =========================================================
|
||||
# BFS
|
||||
# =========================================================
|
||||
|
||||
class BFSStrategy(PathFindingStrategy):
|
||||
|
||||
def find_path(self, maze, start, exit):
|
||||
|
||||
queue = deque([start])
|
||||
|
||||
visited = {start}
|
||||
parent = {}
|
||||
|
||||
visited_count = 0
|
||||
|
||||
while queue:
|
||||
|
||||
current = queue.popleft()
|
||||
|
||||
visited_count += 1
|
||||
|
||||
if current == exit:
|
||||
path = self._restore_path(parent, start, exit)
|
||||
return path, visited_count
|
||||
|
||||
for neighbor in maze.get_neighbors(current):
|
||||
|
||||
if neighbor not in visited:
|
||||
|
||||
visited.add(neighbor)
|
||||
|
||||
parent[neighbor] = current
|
||||
|
||||
queue.append(neighbor)
|
||||
|
||||
return [], visited_count
|
||||
|
||||
@staticmethod
|
||||
def _restore_path(parent, start, exit):
|
||||
|
||||
path = []
|
||||
|
||||
current = exit
|
||||
|
||||
while current != start:
|
||||
path.append(current)
|
||||
current = parent[current]
|
||||
|
||||
path.append(start)
|
||||
|
||||
path.reverse()
|
||||
|
||||
return path
|
||||
|
||||
|
||||
# =========================================================
|
||||
# DFS
|
||||
# =========================================================
|
||||
|
||||
class DFSStrategy(PathFindingStrategy):
|
||||
|
||||
def find_path(self, maze, start, exit):
|
||||
|
||||
stack = [start]
|
||||
|
||||
visited = {start}
|
||||
parent = {}
|
||||
|
||||
visited_count = 0
|
||||
|
||||
while stack:
|
||||
|
||||
current = stack.pop()
|
||||
|
||||
visited_count += 1
|
||||
|
||||
if current == exit:
|
||||
path = self._restore_path(parent, start, exit)
|
||||
return path, visited_count
|
||||
|
||||
for neighbor in maze.get_neighbors(current):
|
||||
|
||||
if neighbor not in visited:
|
||||
|
||||
visited.add(neighbor)
|
||||
|
||||
parent[neighbor] = current
|
||||
|
||||
stack.append(neighbor)
|
||||
|
||||
return [], visited_count
|
||||
|
||||
@staticmethod
|
||||
def _restore_path(parent, start, exit):
|
||||
|
||||
path = []
|
||||
|
||||
current = exit
|
||||
|
||||
while current != start:
|
||||
path.append(current)
|
||||
current = parent[current]
|
||||
|
||||
path.append(start)
|
||||
|
||||
path.reverse()
|
||||
|
||||
return path
|
||||
|
||||
|
||||
# =========================================================
|
||||
# A*
|
||||
# =========================================================
|
||||
|
||||
class AStarStrategy(PathFindingStrategy):
|
||||
|
||||
def heuristic(self, cell: Cell, exit: Cell):
|
||||
|
||||
return abs(cell.x - exit.x) + abs(cell.y - exit.y)
|
||||
|
||||
def find_path(self, maze, start, exit):
|
||||
|
||||
open_set = []
|
||||
|
||||
heappush(open_set, (0, start.x, start.y, start))
|
||||
|
||||
g_score = {
|
||||
start: 0
|
||||
}
|
||||
|
||||
parent = {}
|
||||
|
||||
visited = set()
|
||||
|
||||
visited_count = 0
|
||||
|
||||
while open_set:
|
||||
|
||||
_, _, _, current = heappop(open_set)
|
||||
|
||||
if current in visited:
|
||||
continue
|
||||
|
||||
visited.add(current)
|
||||
|
||||
visited_count += 1
|
||||
|
||||
if current == exit:
|
||||
path = self._restore_path(parent, start, exit)
|
||||
return path, visited_count
|
||||
|
||||
for neighbor in maze.get_neighbors(current):
|
||||
|
||||
tentative_g = g_score[current] + 1
|
||||
|
||||
if (
|
||||
neighbor not in g_score
|
||||
or tentative_g < g_score[neighbor]
|
||||
):
|
||||
|
||||
g_score[neighbor] = tentative_g
|
||||
|
||||
f_score = tentative_g + self.heuristic(
|
||||
neighbor,
|
||||
exit
|
||||
)
|
||||
|
||||
parent[neighbor] = current
|
||||
|
||||
heappush(
|
||||
open_set,
|
||||
(
|
||||
f_score,
|
||||
neighbor.x,
|
||||
neighbor.y,
|
||||
neighbor
|
||||
)
|
||||
)
|
||||
|
||||
return [], visited_count
|
||||
|
||||
@staticmethod
|
||||
def _restore_path(parent, start, exit):
|
||||
|
||||
path = []
|
||||
|
||||
current = exit
|
||||
|
||||
while current != start:
|
||||
path.append(current)
|
||||
current = parent[current]
|
||||
|
||||
path.append(start)
|
||||
|
||||
path.reverse()
|
||||
|
||||
return path
|
||||
56
SorokinAD/[2]lab_2/visualization.py
Normal file
56
SorokinAD/[2]lab_2/visualization.py
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
from abc import ABC, abstractmethod
|
||||
|
||||
from maze import Maze
|
||||
from cell import Cell
|
||||
|
||||
|
||||
class Observer(ABC):
|
||||
|
||||
@abstractmethod
|
||||
def update(self, event: str):
|
||||
|
||||
pass
|
||||
|
||||
|
||||
class ConsoleView(Observer):
|
||||
|
||||
def update(self, event: str):
|
||||
|
||||
print(f"[EVENT]: {event}")
|
||||
|
||||
def render(
|
||||
self,
|
||||
maze: Maze,
|
||||
path: list[Cell] = None,
|
||||
current: Cell = None
|
||||
):
|
||||
|
||||
path = path or []
|
||||
|
||||
path_set = set(path)
|
||||
|
||||
for row in maze.cells:
|
||||
|
||||
line = ""
|
||||
|
||||
for cell in row:
|
||||
|
||||
if current and cell == current:
|
||||
line += "P"
|
||||
|
||||
elif cell.is_start:
|
||||
line += "S"
|
||||
|
||||
elif cell.is_exit:
|
||||
line += "E"
|
||||
|
||||
elif cell.is_wall:
|
||||
line += "#"
|
||||
|
||||
elif cell in path_set:
|
||||
line += "."
|
||||
|
||||
else:
|
||||
line += " "
|
||||
|
||||
print(line)
|
||||
Loading…
Reference in New Issue
Block a user