循环到Python中存储测试结果

时间:2017-02-27 23:49:44

标签: python loops dictionary iteration timeit

简而言之,我需要通过创建每个指定长度(500,1000,10000)的100个随机整数列表来测试一些函数并存储结果。最后,我需要能够计算每次测试的平均执行时间,但我还没有完成代码。

我认为以下是解决此问题的最佳方法:

  1. 创建一个字典以存储所需的列表长度值。
  2. 对于该字典中的每个值,生成一个新的随机整数列表(list_tests)。
  3. 创建另一个字典,用于存储每个功能测试的结果(test_results)。
  4. 使用while循环创建每个长度的100个列表。
  5. 通过调用while循环中的每个函数并将每个结果存储在结果字典中来运行测试。
  6. 该程序似乎运行但我有几个问题:

    • 它永远不会达到其他list_tests值;永远不会超过500。
    • 它覆盖了test_results字典的值

    我不太明白我在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()
    

2 个答案:

答案 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循环不能迭代到另一个值。