循环以在Python中存储测试结果
简而言之,我需要通过创建每个指定长度(500、1000、10000)的100个随机整数列表来测试一些函数,并存储结果。最终,我需要能够计算出每个测试的平均执行时间,但我对代码还没有做到这一点 我认为以下是最好的方法:循环以在Python中存储测试结果,python,loops,dictionary,iteration,timeit,Python,Loops,Dictionary,Iteration,Timeit,简而言之,我需要通过创建每个指定长度(500、1000、10000)的100个随机整数列表来测试一些函数,并存储结果。最终,我需要能够计算出每个测试的平均执行时间,但我对代码还没有做到这一点 我认为以下是最好的方法: 创建字典以存储所需的列表长度值 对于该字典中的每个值,生成一个新的随机整数列表(列表测试) 创建另一个字典,用于存储每个功能测试的结果(测试结果) 使用while循环创建每种长度的100个列表 通过调用while循环中的每个函数并将每个结果存储在结果字典中来运行测试 程序似乎正在运
- 它从未达到其他列表测试值;永远不要超过500
- 它正在覆盖测试结果字典的值
import time
import random
def sequential_search(a_list, item):
start = time.time()
pos = 0
found = False
while pos < len(a_list) and not found:
if a_list[pos] == item:
found = True
else:
pos = pos+1
end = time.time()
return found, end-start
def ordered_sequential_search(a_list, item):
start = time.time()
pos = 0
found = False
stop = False
while pos < len(a_list) and not found and not stop:
if a_list[pos] == item:
found == True
else:
if a_list[pos] > item:
stop = True
else:
pos = pos+1
end = time.time()
return found, end-start
def num_gen(value):
myrandom = random.sample(xrange(0, value), value)
return myrandom
def main():
#new_list = num_gen(10000)
#print(sequential_search(new_list, -1))
list_tests = {'t500': 500, 't1000': 1000, 't10000': 10000}
for i in list_tests.values():
new_list = num_gen(i)
count = 0
test_results = {'seq': 0, 'ordseq': 0}
while count < 100:
test_results['seq'] += sequential_search(new_list, -1)[1]
test_results['ordseq'] += ordered_sequential_search(new_list, -1)[1]
count += 1
if __name__ == '__main__':
main()
导入时间
随机输入
def顺序搜索(列表,项目):
开始=时间。时间()
pos=0
发现=错误
而pos项:
停止=正确
其他:
位置=位置+1
end=time.time()
找到返回,结束开始
def num_gen(值):
myrandom=random.sample(xrange(0,值),value)
返回myrandom
def main():
#新列表=num\u gen(10000)
#打印(顺序搜索(新列表,-1))
列表测试={t500':500,'t1000':1000,'t10000':10000}
对于列表中的i_tests.values():
新列表=数量(i)
计数=0
测试结果={seq':0,'ordseq':0}
当计数小于100时:
测试结果['seq']+=顺序搜索(新列表,-1)[1]
测试结果['ordseq']+=有序顺序搜索(新列表,-1)[1]
计数+=1
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
main()
我想你是说
found = True
而不是
found == True
在线47
另外,for循环更干净。试试这个,它应该是您想要的:
def ordered_sequential_search(a_list, item):
start = time.time()
found = False
stop = False
for i in range(len(a_list)):
if a_list[i] == item:
found = True
else:
if a_list[i] > item:
stop = True
if found: break
if stop: break
end = time.time()
return found, end-start
它正在覆盖字典中的值,因为您指定了覆盖值的键。你没有在字典上附加你本该做的事
您的while循环可能没有中断,这就是为什么for循环无法迭代到另一个值。for循环更合适,这要感谢这一点,但是,搜索函数本身并不是我想要的。我正在尝试为每个搜索函数生成多个输入列表。您是否正在尝试将值列表传递到函数中?是的,我正在尝试将我的num_gen函数创建的列表传递到每个搜索函数中,为每个所需长度500、1000创建100个列表,还有10000。我也有点困惑,你到底想要什么,很抱歉我帮不了你。我建议在你试图修复这个问题之前,先剥离代码,整理一下,删除bug。