简而言之,我需要通过创建每个指定长度(500,1000,10000)的100个随机整数列表来测试一些函数并存储结果。最后,我需要能够计算每次测试的平均执行时间,但我还没有完成代码。
我认为以下是解决此问题的最佳方法:
该程序似乎运行但我有几个问题:
我不太明白我在main()中的循环出错了。我的测试这些功能的过程是否可行?如果是这样,我就失去了如何解决这个循环问题。提前感谢您提供任何帮助!
这是我的计划:
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()
答案 0 :(得分:1)
我认为你的意思是
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
答案 1 :(得分:0)
它会覆盖字典中的值,因为您已指定了覆盖值的键。你没有附加你应该做的字典。
你的while循环可能没有破坏,这就是为什么你的for循环不能迭代到另一个值。