[英]Loop to Store Test Results in Python
In short, I need to test some functions by creating 100 random integer lists of each specified length (500, 1000, 10000) and store the results. 简而言之,我需要通过创建每个指定长度(500、1000、10000)的100个随机整数列表并存储结果来测试某些功能。 Eventually, I need to be able to calculate an average execution time for each test but I've yet to get that far with the code.
最终,我需要能够计算出每个测试的平均执行时间,但是我还没有深入了解代码。
I assumed the following was the best way to approach this: 我认为以下是解决此问题的最佳方法:
The program appears to run but I have a couple problems: 该程序似乎可以运行,但是我有几个问题:
I don't quite understand where I've gone wrong with the loop in main(). 我不太了解main()中的循环在哪里出了问题。 Is my process to test these functions feasible?
我测试这些功能的过程是否可行? If so, I'm lost as to how I can fix this looping problem.
如果是这样,我就无法解决此循环问题。 Thank you in advance for any assistance you can offer!
预先感谢您提供的任何帮助!
Here is my program: 这是我的程序:
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()
I think you meant 我想你是说
found = True
Instead of 代替
found == True
On line 47 47行
Also a for loop is much cleaner try this, it should be what your looking for: 另外,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
It is overwriting values in the dictionary because you have specified the key to overwrite values. 因为您已指定要覆盖值的键,所以它正在覆盖字典中的值。 You are not appending to the dictionary which you should have done.
您没有将本应添加到词典的后面。
Your while loop might not be breaking, that why your for loop cannot iterate to another value. 您的while循环可能不会中断,因此为什么您的for循环无法迭代到另一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.