版权声明: https://blog.csdn.net/u011286584/article/details/82726719
应用前面的 sorts.py
模块完成,详情参阅modules这一篇博文。
定期整理点滴,完善自己,今后给洋哥挣钱,陪伴着让我的小宝贝发自内心爱上笑,加油吧
from sorts import shell, bubble, select, insert, heap
from random import randint
from time import time
from copy import deepcopy
def calculate_time(list):
for i, sort in enumerate(sorts):
array = deepcopy(list)
start_time = time()
globals().get(sort)(array)
end_time = time()
print(sort[i], end_time)
sorts = ['select', 'heap', 'bubble', 'insert', 'shell']
array = [randint(1, 10000) for i in range(10000)]
calculate_time(array)
运行结果
select 3.682133436203003
heap 0.06938433647155762
bubble 11.303961038589478
insert 4.817535400390625
shell 0.08134841918945312
注意:
关于
list
的复制问题
我们在第 8 行使用了array = cpoy(list)
复制数据,为什么不直接用=
呢。假设我们使用=
,结果如下:
运行结果
select 3.7849555015563965
heap 0.07136702537536621
bubble 0.0014972686767578125
insert 0.002495288848876953
shell 0.023456096649169922
除了select
方法正常外,其他的方法运行时间都小了很多,这是为什么。因为这些方法在执行的时候list
已经是有序的了! 算法只不过样子式跑了一圈,因此花费的时间少。究其原因,出现在我们对list
的赋值操作上面。
list 的 ‘=’、‘copy’与‘deepcopy’
list的赋值操作主要有三种,‘=’、拷贝(浅拷贝copy)和深拷贝(deepcopy),我们结合例子来具体说明三种操作:
1、=
2、copy
3、deepcopy
复制出来的与原来的变量相互独立,最清爽的复制
2018.09.16 酉于广州逸夫科学馆