Merge pull request '[1,2] data-structures, maze' (#323) from osininyai/2026-rff_mp:osininyai into develop

Reviewed-on: UNN/2026-rff_mp#323
This commit is contained in:
IvanBoy 2026-05-30 11:28:46 +00:00
commit d801ac985c
23 changed files with 7381 additions and 0 deletions

View File

@ -0,0 +1,28 @@
import random as rd
import string
up=list(string.ascii_uppercase)
consonants=["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"]
vowels=["a", "e", "i", "o", "u", "y"]
count=0
names=[]
while count<5000:
name=""
temp=rd.randint(0, len(up)-1)
name+=up[temp]
length=rd.randint(2,9)
for i in range(length):
temp=rd.randint(0, 1)
if temp==0:
letter=rd.randint(0, len(vowels)-1)
name+=vowels[letter]
else:
letter=rd.randint(0, len(consonants)-1)
name+=consonants[letter]
names.append(name)
count+=1
f=open("names.txt","w")
for i in names:
f.write(i)
f.write("\n")
f.close()

View 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)

View File

@ -0,0 +1,383 @@
from MP_records import records
import random as rd
import time
import csv
import codecs
import sys
sys.setrecursionlimit(15000)
def bst_insert(root,name,phone):
if root==None:
entry={"name":name,"phone":phone,"left":None,"right":None}
root=entry
return root
else:
entry={"name":name,"phone":phone,"left":None,"right":None}
if root["phone"]==phone:
root["name"]=name
return root
else:
if (name.encode())<(root["name"].encode()):
if root["left"]==None:
root["left"]=entry
else:
bst_insert(root["left"], name, phone)
else:
if root["right"]==None:
root["right"]=entry
else:
bst_insert(root["right"], name, phone)
def bst_find(root, name):
a=None
if root!=None:
if root["name"]==name:
return root["phone"]
else:
if (name.encode())>(root["name"].encode()) and root["right"]:
a=bst_find(root["right"], name)
elif root["left"] and a==None:
a=bst_find(root["left"], name)
return a
def bst_delete(root,name):
while root["name"]!=name:
if (name.encode())>(root["name"].encode()):
if root["right"]==None:
#print("None")
return
else:
if root["right"]["name"]==name and root["right"]["right"]==None and root["right"]["left"]==None:
root["right"]=None
return
root=root["right"]
else:
if root["left"]==None:
#print("None")
return
else:
if root["left"]["name"]==name and root["left"]["right"]==None and root["left"]["left"]==None:
root["left"]=None
return
root=root["left"]
if root["right"]:
root1=root["right"]
if root1["left"]:
if root1["left"]["left"]:
while root1["left"]["left"]:
root1=root1["left"]
root2=root1["left"]
else:
root2=root1["left"]
else:
root["name"]=root1["name"]
root["phone"]=root1["phone"]
root["right"]=root1["right"]
return
if root2["right"]:
root["name"]=root2["name"]
root["phone"]=root2["phone"]
root1["left"]=root2["right"]
return
#del root2
else:
root["name"]=root2["name"]
root["phone"]=root2["phone"]
root1["left"]=None
#print(root1.right.data)
return
elif root["left"]:
temp=root["left"]["left"]
root["name"]=root["left"]["name"]
root["phone"]=root["left"]["phone"]
root["right"]=root["left"]["right"]
root["left"]=temp
return
def bst_list_all(root):
if root["left"]:
bst_list_all(root["left"])
print(root["name"]," - ",root["phone"])
if root["right"]:
bst_list_all(root["right"])
def test():
root=None
root=bst_insert(root,"Abba",1)
bst_insert(root,"Babba",2)
bst_insert(root,"Cabba",3)
bst_insert(root,"Aaaaa",4)
bst_insert(root,"Abfga",5)
bst_insert(root,"Arte",6)
bst_insert(root,"Aaxa",7)
bst_insert(root,"Aaax",8)
bst_insert(root,"Aaxx",9)
print(root)
print(bst_find(root, "Aaaaa"))
print(bst_find(root, "Aaxx"))
print(bst_find(root, "Aaax"))
print(bst_find(root, "Babba"))
print(bst_find(root, "Cabba"))
print(bst_find(root, "Arte"))
print(bst_find(root, "Aaxa"))
print(bst_find(root, "Abba"))
print(bst_find(root, "Abfga"))
print(bst_find(root, "Abb"))
#bst_delete(root, "Cabba")
print(root)
bst_list_all(root)
def run_shuffled(records_shuffled):
insertion_times=[]
finding_times=[]
deletion_times1=[]
print("Shuffled list: ")
for k in range(5):
lisst=None
#А. Вставка всех записей
start=time.perf_counter()
lisst=bst_insert(lisst, records_shuffled[0][0], records_shuffled[0][1])
for i in range(1,len(records_shuffled)):
bst_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)):
bst_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()
bst_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"Время (сек)"],
["BinarySearchTree", u"случайный", u"вставка", insertion_times[0]],
["BinarySearchTree", u"случайный", u"вставка", insertion_times[1]],
["BinarySearchTree", u"случайный", u"вставка", insertion_times[2]],
["BinarySearchTree", u"случайный", u"вставка", insertion_times[3]],
["BinarySearchTree", u"случайный", u"вставка", insertion_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["BinarySearchTree", u"случайный", u"вставка", temp,]
]
with codecs.open("docs/data/[1]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"Время (сек)"],
["BinarySearchTree", u"случайный", u"поиск", finding_times[0]],
["BinarySearchTree", u"случайный", u"поиск", finding_times[1]],
["BinarySearchTree", u"случайный", u"поиск", finding_times[2]],
["BinarySearchTree", u"случайный", u"поиск", finding_times[3]],
["BinarySearchTree", u"случайный", u"поиск", finding_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["BinarySearchTree", u"случайный", u"поиск", temp,]
]
with codecs.open("docs/data/[1]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"Время (сек)"],
["BinarySearchTree", u"случайный", u"удаление", del_times[0]],
["BinarySearchTree", u"случайный", u"удаление", del_times[1]],
["BinarySearchTree", u"случайный", u"удаление", del_times[2]],
["BinarySearchTree", u"случайный", u"удаление", del_times[3]],
["BinarySearchTree", u"случайный", u"удаление", del_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["BinarySearchTree", u"случайный", u"удаление", temp,]
]
with codecs.open("docs/data/[1]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=None
#А. Вставка всех записей
start=time.perf_counter()
lisst=bst_insert(lisst, records_shuffled[0][0], records_shuffled[0][1])
for i in range(1,len(records_shuffled)):
bst_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)):
bst_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()
bst_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"Время (сек)"],
["BinarySearchTree", u"отсортированный", u"вставка", insertion_times[0]],
["BinarySearchTree", u"отсортированный", u"вставка", insertion_times[1]],
["BinarySearchTree", u"отсортированный", u"вставка", insertion_times[2]],
["BinarySearchTree", u"отсортированный", u"вставка", insertion_times[3]],
["BinarySearchTree", u"сотсортированный", u"вставка", insertion_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["BinarySearchTree", u"отсортированный", u"вставка", temp,]
]
with codecs.open("docs/data/[1]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"Время (сек)"],
["BinarySearchTree", u"отсортированный", u"поиск", finding_times[0]],
["BinarySearchTree", u"отсортированный", u"поиск", finding_times[1]],
["BinarySearchTree", u"отсортированный", u"поиск", finding_times[2]],
["BinarySearchTree", u"отсортированный", u"поиск", finding_times[3]],
["BinarySearchTree", u"отсортированный", u"поиск", finding_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["BinarySearchTree", u"отсортированный", u"поиск", temp,]
]
with codecs.open("docs/data/[1]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"Время (сек)"],
["BinarySearchTree", u"отсортированный", u"удаление", del_times[0]],
["BinarySearchTree", u"отсортированный", u"удаление", del_times[1]],
["BinarySearchTree", u"отсортированный", u"удаление", del_times[2]],
["BinarySearchTree", u"отсортированный", u"удаление", del_times[3]],
["BinarySearchTree", u"отсортированный", u"удаление", del_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["BinarySearchTree", u"отсортированный", u"удаление", temp,]
]
with codecs.open("docs/data/[1]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)

View File

@ -0,0 +1,452 @@
from MP_records import records
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):
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("docs/data/[1]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("docs/data/[1]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("docs/data/[1]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 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("docs/data/[1]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("docs/data/[1]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("docs/data/[1]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)

View File

@ -0,0 +1,434 @@
from MP_records import records
import random as rd
import time
import csv
import codecs
def insert(lisst,name,phone):
if len(lisst)==0:
entry={"name":name,"phone":phone,"next":None}
lisst.append(entry)
return lisst
else:
entry={"name":name,"phone":phone,"next":None}
if lisst[0]["phone"]==phone:
lisst[0]["name"]=name
return lisst
if lisst[0]["next"]==None:
lisst[0]["next"]=entry
return lisst
else:
nexxt=lisst[0]["next"]
if nexxt["phone"]==phone:
nexxt["name"]=name
return lisst
while nexxt["next"]!=None:
nexxt=nexxt["next"]
if nexxt["phone"]==phone:
nexxt["name"]=name
return lisst
nexxt["next"]=entry
return lisst
def find(lisst, name):
if len(lisst)>0:
if lisst[0]["name"]==name:
return lisst[0]["phone"]
elif lisst[0]["next"]!=None:
nexxt=lisst[0]["next"]
while nexxt["next"]!=None:
if nexxt["name"]==name:
return nexxt["phone"]
else:
nexxt=nexxt["next"]
if nexxt["name"]==name:
return nexxt["phone"]
return None
def delete(lisst,name):
if len(lisst)>0:
if lisst[0]["name"]==name:
if lisst[0]["next"]!=None:
lisst[0]=lisst[0]["next"]
return lisst
else:
lisst.pop()
return lisst
elif lisst[0]["next"]!=None:
if lisst[0]["next"]["name"]==name:
if lisst[0]["next"]["next"]!=None:
lisst[0]["next"]=lisst[0]["next"]["next"]
return lisst
else:
lisst[0]["next"]=None
return lisst
elif lisst[0]["next"]["next"]!=None:
nexxt1=lisst[0]["next"]
nexxt2=nexxt1["next"]
if nexxt2["name"]==name:
if nexxt2["next"]!=None:
nexxt1["next"]=nexxt2["next"]
return lisst
else:
nexxt1["next"]=None
return lisst
while nexxt2["next"]!=None:
nexxt1=nexxt2
nexxt2=nexxt1["next"]
if nexxt2["name"]==name:
if nexxt2["next"]!=None:
nexxt1["next"]=nexxt2["next"]
return lisst
else:
nexxt1["next"]=None
return lisst
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 list_all(lisst):
names=[]
phones=[]
if len(lisst)>0:
names.append(lisst[0]["name"])
phones.append(lisst[0]["phone"])
nexxt=lisst[0]["next"]
while nexxt!=None:
names.append(nexxt["name"])
phones.append(nexxt["phone"])
nexxt=nexxt["next"]
else:
print("List is empty")
return
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():
lisst=[]
insert(lisst,"Abba",1)
insert(lisst,"Cafr",43)
insert(lisst,"Babba",2)
insert(lisst,"V",2)
insert(lisst,"Babadsaba",3)
insert(lisst,"Cabr",34)
insert(lisst,"Aaaaa",4)
insert(lisst,"Ba",5)
a=find(lisst,"Aaaaa")
print(a)
print(lisst,'\n')
delete(lisst,"Abba")
# print(lisst,'\n')
# delete("Aaaaa")
# print(lisst,'\n')
# delete("Ba")
# print(lisst,'\n')
# delete("Babadsaba")
# print(lisst,'\n')
delete(lisst,"Aaaaa")
# print(lisst,'\n')
list_all(lisst)
print(lisst,'\n')
def run_shuffled(records_shuffled):
insertion_times=[]
finding_times=[]
deletion_times1=[]
print("Shuffled list: ")
for k in range(5):
lisst=[]
rd.shuffle(records_shuffled)
#А. Вставка всех записей
start=time.perf_counter()
for i in range(len(records_shuffled)):
insert(lisst, records_shuffled[i][0], records_shuffled[i][1])
end=time.perf_counter()
insertion_times.append(end-start)
#Б. Поиск 100 случайных записей
names=[]
for i in range(100):
index=rd.randint(0,9999)
name=lisst[0]
while index>0:
name=name["next"]
index-=1
names.append(name["name"])
for i in range(10):
names.append("A")
rd.shuffle(names)
start=time.perf_counter()
for i in range(len(names)):
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()
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"Время (сек)"],
["LinkedList", u"случайный", u"вставка", insertion_times[0]],
["LinkedList", u"случайный", u"вставка", insertion_times[1]],
["LinkedList", u"случайный", u"вставка", insertion_times[2]],
["LinkedList", u"случайный", u"вставка", insertion_times[3]],
["LinkedList", u"случайный", u"вставка", insertion_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["LinkedList", u"случайный", u"вставка", temp,]
]
with codecs.open("docs/data/[1]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"Время (сек)"],
["LinkedList", u"случайный", u"поиск", finding_times[0]],
["LinkedList", u"случайный", u"поиск", finding_times[1]],
["LinkedList", u"случайный", u"поиск", finding_times[2]],
["LinkedList", u"случайный", u"поиск", finding_times[3]],
["LinkedList", u"случайный", u"поиск", finding_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["LinkedList", u"случайный", u"поиск", temp,]
]
with codecs.open("docs/data/[1]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"Время (сек)"],
["LinkedList", u"случайный", u"удаление", del_times[0]],
["LinkedList", u"случайный", u"удаление", del_times[1]],
["LinkedList", u"случайный", u"удаление", del_times[2]],
["LinkedList", u"случайный", u"удаление", del_times[3]],
["LinkedList", u"случайный", u"удаление", del_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["LinkedList", u"случайный", u"удаление", temp,]
]
with codecs.open("docs/data/[1]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=[]
#А. Вставка всех записей
start=time.perf_counter()
for i in range(len(records_shuffled)):
insert(lisst, records_shuffled[i][0], records_shuffled[i][1])
end=time.perf_counter()
insertion_times.append(end-start)
#Б. Поиск 100 случайных записей
names=[]
for i in range(100):
index=rd.randint(0,9999)
name=lisst[0]
while index>0:
name=name["next"]
index-=1
names.append(name["name"])
for i in range(10):
names.append("A")
rd.shuffle(names)
start=time.perf_counter()
for i in range(len(names)):
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()
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"Время (сек)"],
["LinkedList", u"отсортированный", u"вставка", insertion_times[0]],
["LinkedList", u"отсортированный", u"вставка", insertion_times[1]],
["LinkedList", u"отсортированный", u"вставка", insertion_times[2]],
["LinkedList", u"отсортированный", u"вставка", insertion_times[3]],
["LinkedList", u"сотсортированный", u"вставка", insertion_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["LinkedList", u"отсортированный", u"вставка", temp,]
]
with codecs.open("docs/data/[1]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"Время (сек)"],
["LinkedList", u"отсортированный", u"поиск", finding_times[0]],
["LinkedList", u"отсортированный", u"поиск", finding_times[1]],
["LinkedList", u"отсортированный", u"поиск", finding_times[2]],
["LinkedList", u"отсортированный", u"поиск", finding_times[3]],
["LinkedList", u"отсортированный", u"поиск", finding_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["LinkedList", u"отсортированный", u"поиск", temp,]
]
with codecs.open("docs/data/[1]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"Время (сек)"],
["LinkedList", u"отсортированный", u"удаление", del_times[0]],
["LinkedList", u"отсортированный", u"удаление", del_times[1]],
["LinkedList", u"отсортированный", u"удаление", del_times[2]],
["LinkedList", u"отсортированный", u"удаление", del_times[3]],
["LinkedList", u"отсортированный", u"удаление", del_times[4]],
[u"Структура", u"Режим", u"Операция", u"Среднее время (сек)"],
["LinkedList", u"отсортированный", u"удаление", temp,]
]
with codecs.open("docs/data/[1]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)

Binary file not shown.

Binary file not shown.

Binary file not shown.
Can't render this file because it has a wrong number of fields in line 9.

File diff suppressed because it is too large Load Diff

4
osininyai/[2] maze/1.txt Normal file
View File

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

10
osininyai/[2] maze/2.txt Normal file
View File

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

View File

@ -0,0 +1,142 @@
import random as rd
def CreateMazeFile(size):
if size==10:
with open("maze_10x10.txt","w") as f:
for i in range(size):
line=""
for j in range(size):
temp=rd.randint(0, 2)
if temp==2:
line+="#"
else:
line+=" "
if i==0:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="E"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
elif i==size-1:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="S"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
line+="\n"
f.write(line)
elif size==50:
with open("maze_50x50.txt","w") as f:
for i in range(size):
line=""
for j in range(size):
temp=rd.randint(0, 5)
if temp>3:
line+="#"
else:
line+=" "
if i==0:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="E"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
elif i==size-1:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="S"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
line+="\n"
f.write(line)
elif size==100:
with open("maze_100x100.txt","w") as f:
for i in range(size):
line=""
for j in range(size):
temp=rd.randint(0, 5)
if temp>3:
line+="#"
else:
line+=" "
if i==0:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="E"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
elif i==size-1:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="S"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
line+="\n"
f.write(line)
elif size==0:
with open("maze_no_walls.txt","w") as f:
size=rd.randint(10, 100)
for i in range(size):
line=""
for j in range(size):
line+=" "
if i==0:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="E"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
elif i==size-1:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="S"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
line+="\n"
f.write(line)
elif size==-1:
with open("maze_no_exit.txt","w") as f:
size=rd.randint(10, 100)
for i in range(size):
line=""
for j in range(size):
temp=rd.randint(0, 5)
if temp>3:
line+="#"
else:
line+=" "
if i==size-1:
l=list(line)
temp=rd.randint(1, size-2)
l[temp]="S"
line1=""
for k in range(len(line)):
line1+=l[k]
line=line1
line+="\n"
f.write(line)
CreateMazeFile(10) #10x10
CreateMazeFile(50) #50x50
CreateMazeFile(100) #100x100
CreateMazeFile(0) #no walls
CreateMazeFile(-1) #no exit

View File

@ -0,0 +1,499 @@
import heapq
import time
import codecs
import csv
class Cell:
def __init__(self,x,y,isWall,isStart,isExit):
self.x=x
self.y=y
self.isWall=isWall
self.isStart=isStart
self.isExit=isExit
def isPassable(self):
if self.isWall==False:
return True
else:
return False
class Maze:
def __init__(self,grid):
self.grid=grid
self.width=len(self.grid[0])
self.height=len(self.grid)
self.start=None
self.exit=None
for i in range(self.height):
for j in range(self.width):
if self.grid[i][j].isStart==True:
self.start=(j,i)
if self.grid[i][j].isExit==True:
self.exit=(j,i)
def getCell(self,x,y):
return self.grid[y][x]
def getNeighbours(self,cell):
x=cell.x
y=cell.y
cell_up=None
cell_down=None
cell_left=None
cell_right=None
#up
if y>0:
if self.grid[y-1][x].isPassable()==True:
cell_up=self.grid[y-1][x]
#down
if y<(self.height-1):
if self.grid[y+1][x].isPassable()==True:
cell_down=self.grid[y+1][x]
#left
if x>0:
if self.grid[y][x-1].isPassable()==True:
cell_left=self.grid[y][x-1]
#right
if x<(self.width-1):
if self.grid[y][x+1].isPassable()==True:
cell_right=self.grid[y][x+1]
#neighbours=[cell_up, cell_down, cell_left, cell_right]
neighbours=[cell_down, cell_right, cell_up, cell_left]
return neighbours
class TextFileMazeBuilder:
def build(self,filename):
with open(filename,"r") as f:
lines=f.readlines()
grid=[]
x=0
y=0
for i in range(len(lines)):
line=lines[i]
x=0
row=[]
for j in range(len(line)):
if line[j]=="#":
row.append(Cell(x,y,True,False,False))
elif line[j]==" ":
row.append(Cell(x,y,False,False,False))
elif line[j]=="S":
row.append(Cell(x,y,False,True,False))
elif line[j]=="E":
row.append(Cell(x,y,False,False,True))
x+=1
grid.append(row)
y+=1
return grid
class MazeBuilder:
def buildFromFile(self,filename):
grid = TextFileMazeBuilder().build(filename)
return Maze(grid)
class SearchStats:
def __init__(self,ttime,visited_cells,path_length):
self.ttime=ttime
self.visited_cells=visited_cells
self.path_length=path_length
class BFSStrategy:
def findPath(self,maze,start,exxit):
tstart=time.perf_counter()
queue=[]
queue.append((maze.getCell(start[0],start[1]),0))
visited_cells=[maze.getCell(start[0],start[1])]
Path={}
f=0
count=0
while len(queue)!=0:
temp=queue.pop(0)
cell=temp[0]
steps=temp[1]
directions=maze.getNeighbours(cell)
count+=1
if (cell.x,cell.y)==exxit:
end=time.perf_counter()
#print(end-tstart)
f=1
break
for i in directions:
if i!=None:
flag=0
for j in visited_cells:
if i==j:
flag=1
break
if flag==0:
queue.append((i,steps+1))
visited_cells.append(i)
Path[(i.x,i.y)]=(cell.x,cell.y)
reversePath=[]
if f==1:
cell=exxit
while cell!=start:
reversePath.append(cell)
cell=Path[cell]
reversePath.append(cell)
reversePath.reverse()
#print(len(reversePath)-1)
return reversePath, count
class DFSStrategy:
def findPath(self,maze,start,exxit):
tstart=time.perf_counter()
queue=[]
queue.append((maze.getCell(start[0],start[1]),0))
visited_cells=[maze.getCell(start[0],start[1])]
Path={}
f=0
count=0
while len(queue)!=0:
temp=queue.pop()
cell=temp[0]
steps=temp[1]
directions=maze.getNeighbours(cell)
count+=1
if (cell.x,cell.y)==exxit:
end=time.perf_counter()
#print(end-tstart)
f=1
break
for i in directions:
if i!=None:
flag=0
for j in visited_cells:
if i==j:
flag=1
break
if flag==0:
queue.append((i,steps+1))
visited_cells.append(i)
Path[(i.x,i.y)]=(cell.x,cell.y)
reversePath=[]
if f==1:
cell=exxit
while cell!=start:
reversePath.append(cell)
cell=Path[cell]
reversePath.append(cell)
reversePath.reverse()
#print(len(reversePath)-1)
return reversePath, count
class AStarStrategy:
def H(self,exxit,cell):
Hn=0
if exxit!=None:
Hn=abs(exxit[0]-cell.x)+abs(exxit[1]-cell.y)
return Hn
def findPath(self,maze,start,exxit):
tstart=time.perf_counter()
queue=[]
f=self.H(exxit,maze.getCell(start[0],start[1]))
heapq.heappush(queue, (f, f, (start[0],start[1])))
f_scores=[]
for i in range(maze.height):
row=[]
for j in range(maze.width):
row.append(None)
f_scores.append(row)
g_scores=[]
for i in range(maze.height):
row=[]
for j in range(maze.width):
row.append(None)
g_scores.append(row)
f_scores[start[1]][start[0]]=f
g_scores[start[1]][start[0]]=0
Path={}
flag=0
count=0
while len(queue)!=0:
temp=heapq.heappop(queue)
cell=temp[2]
directions=maze.getNeighbours(maze.getCell(cell[0], cell[1]))
count+=1
if (cell[0],cell[1])==exxit:
end=time.perf_counter()
#print(end-tstart)
flag=1
break
for i in directions:
if i!=None:
temp_g=g_scores[cell[1]][cell[0]]+1
temp_f=temp_g+self.H(exxit,i)
if f_scores[i.y][i.x]==None:
g_scores[i.y][i.x]=temp_g
f_scores[i.y][i.x]=temp_f
heapq.heappush(queue,(temp_f,self.H(exxit,i),(i.x,i.y)))
Path[(i.x,i.y)]=cell
elif temp_f<f_scores[i.y][i.x]:
f_scores[i.y][i.x]=temp_f
g_scores[i.y][i.x]=temp_g
heapq.heappush(queue,(temp_f,self.H(exxit,i),(i.x,i.y)))
Path[(i.x,i.y)]=cell
reversePath=[]
if flag==1:
cell=exxit
while cell!=start:
reversePath.append(cell)
cell=Path[cell]
reversePath.append(cell)
reversePath.reverse()
#print(len(reversePath)-1)
return reversePath, count
class PathFindingStrategy:
def __init__(self,strategy):
self.strategy=strategy
def findPath(self,maze,start,exxit):
if self.strategy=="BFS":
return BFSStrategy().findPath(maze,start,exxit)
elif self.strategy=="DFS":
return DFSStrategy().findPath(maze,start,exxit)
elif self.strategy=="AStar":
return AStarStrategy().findPath(maze,start,exxit)
class MazeSolver:
def __init__(self, maze, strategy):
self.maze=maze
self.strategy=PathFindingStrategy(strategy)
def setStrategy(self, strategy):
self.strategy=PathFindingStrategy(strategy)
def solve(self):
start=time.perf_counter()
path, visited = self.strategy.findPath(self.maze, self.maze.start, self.maze.exit)
end=time.perf_counter()
if len(path)>0:
path_length=len(path)-1
else:
path_length=0
return SearchStats(end-start, visited, path_length)
def test():
#maze=MazeBuilder().buildFromFile("1.txt")
#maze=MazeBuilder().buildFromFile("2.txt")
maze=MazeBuilder().buildFromFile("v.txt")
#maze=MazeBuilder().buildFromFile("maze_10x10.txt")
#maze=MazeBuilder().buildFromFile("maze_50x50.txt")
#maze=MazeBuilder().buildFromFile("maze_100x100.txt")
#maze=MazeBuilder().buildFromFile("maze_no_walls.txt")
#maze=MazeBuilder().buildFromFile("maze_no_exit.txt")
print(maze.exit)
print(maze.start)
stats=MazeSolver(maze, "BFS").solve()
print(stats.ttime,stats.visited_cells,stats.path_length)
stats=MazeSolver(maze, "DFS").solve()
print(stats.ttime,stats.visited_cells,stats.path_length)
stats=MazeSolver(maze, "AStar").solve()
print(stats.ttime,stats.visited_cells,stats.path_length)
#print(PathFindingStrategy("BFS").findPath(maze,maze.start,maze.exit))
#print(PathFindingStrategy("DFS").findPath(maze,maze.start,maze.exit))
#print(PathFindingStrategy("AStar").findPath(maze,maze.start,maze.exit))
#PathFindingStrategy("BFS").findPath(maze,maze.start,maze.exit)
#PathFindingStrategy("DFS").findPath(maze,maze.start,maze.exit)
#PathFindingStrategy("AStar").findPath(maze,maze.start,maze.exit)
def run():
maze=MazeBuilder().buildFromFile("maze_10x10.txt")
results = [
[u"Лабиринт", u"Стратегия", u"Среднее время (мс)", u"Посещено клеток",u"Длина пути"]
]
temp=0
for i in range(10):
stats=MazeSolver(maze, "BFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["10x10", "BFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "DFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["10x10", "DFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "AStar").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["10x10", "AStar", temp, stats.visited_cells, stats.path_length])
with codecs.open("docs/data/[2]results.csv", "w", "utf-16") as f:
writer = csv.writer(f)
writer.writerows(results)
writer.writerow("")
maze=MazeBuilder().buildFromFile("maze_50x50.txt")
results = []
temp=0
for i in range(10):
stats=MazeSolver(maze, "BFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["50x50", "BFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "DFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["50x50", "DFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "AStar").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["50x50", "AStar", temp, stats.visited_cells, stats.path_length])
with codecs.open("docs/data/[2]results.csv", "a+", "utf-16") as f:
writer = csv.writer(f)
writer.writerows(results)
writer.writerow("")
maze=MazeBuilder().buildFromFile("maze_100x100.txt")
results = []
temp=0
for i in range(10):
stats=MazeSolver(maze, "BFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["100x100", "BFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "DFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["100x100", "DFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "AStar").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append(["100x100", "AStar", temp, stats.visited_cells, stats.path_length])
with codecs.open("docs/data/[2]results.csv", "a+", "utf-16") as f:
writer = csv.writer(f)
writer.writerows(results)
writer.writerow("")
maze=MazeBuilder().buildFromFile("maze_no_walls.txt")
results = []
temp=0
for i in range(10):
stats=MazeSolver(maze, "BFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append([u"Без стен", "BFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "DFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append([u"Без стен", "DFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "AStar").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append([u"Без стен", "AStar", temp, stats.visited_cells, stats.path_length])
with codecs.open("docs/data/[2]results.csv", "a+", "utf-16") as f:
writer = csv.writer(f)
writer.writerows(results)
writer.writerow("")
maze=MazeBuilder().buildFromFile("maze_no_exit.txt")
results = []
temp=0
for i in range(10):
stats=MazeSolver(maze, "BFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append([u"Без выхода", "BFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "DFS").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append([u"Без выхода", "DFS", temp, stats.visited_cells, stats.path_length])
temp=0
for i in range(10):
stats=MazeSolver(maze, "AStar").solve()
temp+=stats.ttime
temp=temp/10
temp=temp*(10**3)
results.append([u"Без выхода", "AStar", temp, stats.visited_cells, stats.path_length])
with codecs.open("docs/data/[2]results.csv", "a+", "utf-16") as f:
writer = csv.writer(f)
writer.writerows(results)
writer.writerow("")
run()

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.
1 Лабиринт Стратегия Среднее время (мс) Посещено клеток Длина пути
2 10x10 BFS 0.3112600003078114 63 13
3 10x10 DFS 0.06941999890841544 20 17
4 10x10 AStar 0.09370000043418258 18 13
5 50x50 BFS 58.025890000863 996 126
6 50x50 DFS 44.11626000000979 803 226
7 50x50 AStar 4.086630000529112 985 126
8 100x100 BFS 1913.4049600012077 6324 166
9 100x100 DFS 301.5443399992364 2264 934
10 100x100 AStar 11.337080000521382 2616 166
11 Без стен BFS 131.18172000104096 1346 48
12 Без стен DFS 1.992550001887139 129 128
13 Без стен AStar 0.4591400007484481 49 48
14 Без выхода BFS 1.9435000001976732 190 0
15 Без выхода DFS 2.0225300002493896 190 0
16 Без выхода AStar 0.5684099996869918 190 0

View File

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

View File

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

View File

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

View File

@ -0,0 +1,17 @@
##
# # # ##
## ### # # #
# # # # # #
# ## #
### ## # #
# # # # # #
# ### #
# ## ##
## # # #
### # # #
## ## #
# # ## #
## # #
# # ## ### ###
# # # ## #
# #S##

View File

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

132
osininyai/[2] maze/v.txt Normal file
View File

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