【问题标题】:get execution time of bubble sort获取冒泡排序的执行时间
【发布时间】:2022-10-21 20:36:14
【问题描述】:

我正在尝试打印冒泡排序的执行时间,但它一直在询问整数

“TypeError:需要一个整数(获取类型 NoneType)”

import time


def bubbleSort(array):
    # loop to access each array element
    for i in range(len(array)):

        # loop to compare array elements
        for j in range(0, len(array) - i - 1):

            # compare two adjacent elements
            # change > to < to sort in descending order
            if array[j] > array[j + 1]:
                # swapping elements if elements
                # are not in the intended order
                temp = array[j]
                array[j] = array[j + 1]
                array[j + 1] = temp


def get_time(arg):
    start = time.time()
    time.sleep(arg) 
    end = time.time()
    return end-start

time = get_time(bubbleSort(list))
print(time)

【问题讨论】:

  • get_time(bubbleSort(list)) 应该做什么?你为什么在 get_time 睡觉?什么是清单?如果有的话,你应该叫它get_time(list) 并让 get_time 做bubbleSort(arg) 而不是睡觉。
  • 你的bubbleSort 函数没有返回值,你没有显示回溯,但我认为这是意外的None 的来源(即你将None 传递给get_time
  • list 是 Python 内置的,所以 bubbleSort(list) 看起来不对 - 如果您在其中存储了一个列表,请为您的变量使用不同的名称
  • 使用docs.python.org/3/library/timeit.html 来衡量代码的性能,它会比自己编写时序代码产生更好的结果
  • 正如@luk2302 所说,您的get_time 函数无法测量bubbleSort 的执行时间,因为函数调用的方式是首先调用bubbleSort,然后将其结果传递给get_time,所以@987654336 @ 只是测量睡眠时间......如果你想编写自己的,它需要实现为装饰器或上下文管理器

标签: python


【解决方案1】:

您的程序没有按照您认为的方式运行:

您似乎正在尝试的是让get_time() 等到bubbleSort() 完成。因此在其中调用了time.sleep()

实际发生的是,最里面的函数bubbleSort() 首先被调用,它的返回值——None被传递给get_time()函数。

这是固定的 get_time 调用:

def get_time():
    start = time.time()
    bubbleSort(list)
    end = time.time()
    return end-start

time = get_time()

【讨论】:

    猜你喜欢
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    相关资源
    最近更新 更多