2017-02-27 166 views
0

簡而言之,我需要通過創建100個隨機指定長度的整數列表(500,1000,10000)並存儲結果來測試一些函數。最終,我需要能夠計算每個測試的平均執行時間,但是我還沒有在代碼中獲得那麼多。循環以Python存儲測試結果

我認爲以下是接近最好的辦法:

  1. 創建字典存儲所需的列表長度值。
  2. 對於該字典中的每個值,生成一個隨機整數(list_tests)的新列表。
  3. 創建另一個字典用於存儲每個功能測試(test_results)的結果。
  4. 使用while循環創建每個長度的100個列表。
  5. 通過在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() 
+0

一個「for」循環會更合適 –

回答

1

我認爲你的意思

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 
+0

感謝這一點,但是,搜索功能本身並不完全是我所追求的。我試圖找出如何爲每個搜索函數生成多個輸入列表。 – notaprogrammr

+0

你是否試圖將一個值列表傳遞給一個函數? –

+0

是的,我試圖將由我的num_gen函數創建的列表傳遞到每個搜索函數中,爲每個需要的長度爲500,1000和10000創建100個列表。 – notaprogrammr

0

它覆蓋字典中的值,因爲你已經指定了覆蓋值的鍵。你並不追求你應該完成的字典。

你的while循環可能不會中斷,那爲什麼你的for循環不能迭代到另一個值。