循环以Python存储测试结果
简而言之,我需要通过创建100个随机指定长度的整数列表(500,1000,10000)并存储结果来测试一些函数。最终,我需要能够计算每个测试的平均执行时间,但是我还没有在代码中获得那么多。循环以Python存储测试结果
我认为以下是接近最好的办法:
- 创建字典存储所需的列表长度值。
- 对于该字典中的每个值,生成一个随机整数(list_tests)的新列表。
- 创建另一个字典用于存储每个功能测试(test_results)的结果。
- 使用while循环创建每个长度的100个列表。
- 通过在while循环中调用每个函数并将每个结果存储在结果字典中来运行测试。
的程序似乎运行,但我有几个问题:
- 它从来没有达到其他list_tests值;从来没有进行超越500
- 它覆盖值的test_results字典
我不太明白的地方,我在主了毛病环()。测试这些功能的过程是否可行?如果是这样,我失去了如何解决这个循环问题。预先感谢您提供的任何帮助!
这里是我的程序:
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()
我认为你的意思
found = True
而不是
found == True
线也是一个for循环47
干净多了试试这个,它应该是你要找的:
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
感谢这一点,但是,搜索功能本身并不完全是我所追求的。我试图找出如何为每个搜索函数生成多个输入列表。 – notaprogrammr
你是否试图将一个值列表传递给一个函数? –
是的,我试图将由我的num_gen函数创建的列表传递到每个搜索函数中,为每个需要的长度为500,1000和10000创建100个列表。 – notaprogrammr
它覆盖字典中的值,因为你已经指定了覆盖值的键。你并不追求你应该完成的字典。
你的while循环可能不会中断,那为什么你的for循环不能迭代到另一个值。
一个“for”循环会更合适 –