该程序将分析不同情况下的不同排序算法。 我想存储算法名称,我需要为案例(a)存储10个运行时间值,然后分别存储10个运行值,用于案例(b) 下面是测试不同排序算法运行时的代码。我的代码在每个算法启动后都会丢失结果,因为我不知道如何正确存储它们
def call(m):
for i in range(m):
makelist()
def makelist():
lst=[10]
for l in lst:
testall(l)
def testall(n):
flist = [insertionsort,selectionsort]
if n < 1:
n = 1
testlist = [i for i in range(n)]
lsr=[testlist.sort(), testlist.sort(reverse=True),random.shuffle(testlist)]
for f in flist:
result=[]
for g in lsr:
copylist = copy.deepcopy(testlist)
testfunction(copylist,f, result)
def testfunction(testlist, function,r):
start_time = time.perf_counter()
function(testlist)
end_time = time.perf_counter()
print('time =', (end_time - start_time), '; alg =', function.__name__, '(', len(testlist), ')')
r.append(end_time - start_time)
答案 0 :(得分:0)
根据您的大纲,我建议使用列表的默认值,其中函数名称是键,并且各种计时附加到值:
from collections import defaultdict
def testfunction(testlist, function, results):
start_time = time.perf_counter()
function(testlist)
end_time = time.perf_counter()
print('time =', (end_time - start_time), '; alg =', function.__name__, '(', len(testlist), ')')
results[function.__name__].append(end_time - start_time)
results = defaultdict(list)
for f in flist:
for g in lsr:
copylist = copy.deepcopy(testlist)
testfunction(copylist, f, results)
当您完成后,结果将包含以下内容:
>>> results
defaultdict(<class 'list'>, {'haresort': [6.194799953483277, 1.947999534832776, 9.47999534832776, 4.799953483277619, 7.999534832776194, 6.194799953483277, 1.947999534832776, 9.47999534832776, 4.799953483277619, 7.999534832776194], 'snailsort': [8.327761947999534, 3.277619479995348, 2.776194799953483, 7.761947999534832, 7.619479995348327, 8.327761947999534, 3.277619479995348, 2.776194799953483, 7.761947999534832, 7.619479995348327]})
在大多数情况下,只需将defaultdict视为普通字典即可。例如,作为testall()中的最后一件事,您可以打印出结果的内容:
for function, timings in results.items():
print(function, ":\n")
print(*timings, sep="\n")
print()