簡而言之,我需要通過創建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()
一個「for」循環會更合適 –