繁体   English   中英

循环将测试结果存储在Python中

[英]Loop to Store Test Results in Python

简而言之,我需要通过创建每个指定长度(500、1000、10000)的100个随机整数列表并存储结果来测试某些功能。 最终,我需要能够计算出每个测试的平均执行时间,但是我还没有深入了解代码。

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

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

该程序似乎可以运行,但是我有几个问题:

  • 它永远不会达到其他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()

我想你是说

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

因为您已指定要覆盖值的键,所以它正在覆盖字典中的值。 您没有将本应添加到词典的后面。

您的while循环可能不会中断,因此为什么您的for循环无法迭代到另一个值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM