【发布时间】: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