【问题标题】:Loop to Store Test Results in Python在 Python 中循环存储测试结果
【发布时间】:2017-02-27 23:49:43
【问题描述】:

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

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

  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()

【问题讨论】:

  • 一个“for”循环会更合适

标签: python loops dictionary iteration timeit


【解决方案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

【讨论】:

  • 感谢您,但是,搜索功能本身并不是我所追求的。我正在尝试研究如何为每个搜索功能生成多个输入列表。
  • 您是否尝试将值列表传递给函数?
  • 是的,我正在尝试将我的 num_gen 函数创建的列表传递给每个搜索函数,为每个所需长度 500、1000 和 10000 创建 100 个列表。
  • 对你到底想要什么有点困惑,抱歉我帮不了你。
  • 我建议在尝试修复此问题之前剥离代码、整理并删除错误。
【解决方案2】:

它正在覆盖字典中的值,因为您已经指定了覆盖值的键。你没有附加到你应该做的字典。

您的 while 循环可能没有中断,这就是为什么您的 for 循环无法迭代到另一个值的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-25
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 2010-09-11
    • 2021-01-03
    相关资源
    最近更新 更多