# 方式一:耗时特别长 for a in range(0,1001): for b in range(0,1001): for c in range(0,1001): if a+b+c == 1000 and a**2+b**2 == c**2: print(a,b,c) # 方式二:耗时特别短 for a in range(0,1001): for b in range(0,1001): c = 1000-a-b if a+b+c == 1000 and a**2+b**2 == c**2: print(a,b,c) 0 500 500 200 375 425 375 200 425 500 0 500
def sumOfN(n): theSum = 0 # 执行步骤 1 次 for i in range(1,n+1): theSum = theSum + i # 执行步骤 n 次 return theSum print(sumOfN(10)) # 总的执行步骤 n+1 次 # O(n) 括号内放计算执行步骤最有意义的项 # 这串代码执行的算法数量为O(n) a=5 b=6 c=10 # 3 for i in range(n): for j in range(n): # 3*n**2 x = i * i y = j * j z = i * j for k in range(n): # 2*n w = a*k + 45 v = b*b d = 33 # 1 # 4+2n+3n**2 # O(n**2)
本节的目标是告诉大家Python列表和字典操作的 大O 性能。然后我们将做一些基于时间的实验来说明每个数据结构的花销和使用这些数据结构的好处
timeit模块:该模块可以用来测试一段python代码的执行速度/时长。
Timer类:该类是timeit模块中专门用于测量python代码的执行速度/时长的。原型为:class timeit.Timer(stmt=‘pass‘,setup=‘pass‘)。
stmt参数:表示即将进行测试的代码块语句。
setup:运行代码块语句时所需要的设置。
timeit函数:timeit.Timer.timeit(number=100000),该函数返回代码块语句执行number次的平均耗时。
def test01(): alist = [] for i in range(1000): alist.append(i) def test02(): alist = [] for i in range(1000): alist = alist + [i] def test03(): alist = [i for i in range(1000)] def test04(): alist = list(range(1000)) #四种方式中哪种方式添加列表元素的效率最高呢? from timeit import Timer if __name__ == ‘__main__‘: t1 = Timer(‘test01()‘,‘from __main__ import test01‘) print(t1.timeit(1000)) t1 = Timer(‘test02()‘,‘from __main__ import test02‘) print(t1.timeit(1000)) t1 = Timer(‘test03()‘,‘from __main__ import test03‘) print(t1.timeit(1000)) t1 = Timer(‘test04()‘,‘from __main__ import test04‘) print(t1.timeit(1000)) 0.0860275 1.4280624 0.03301989999999999 0.014072400000000096
# 方式一 需要遍历才能找到目标信息 时间复杂度为O(n) [{ ‘name‘:‘xxx‘, ‘score‘:‘xxx‘ },{ ‘name‘:‘xxx‘, ‘score‘:‘xxx‘ },{ ‘name‘:‘xxx‘, ‘score‘:‘xxx‘ }] [{‘name‘: ‘xxx‘, ‘score‘: ‘xxx‘}, {‘name‘: ‘xxx‘, ‘score‘: ‘xxx‘}, {‘name‘: ‘xxx‘, ‘score‘: ‘xxx‘}] # 方式二:同上 时间复杂度为O(n) [ (‘name‘,‘score‘), (‘name‘,‘score‘), (‘name‘,‘score‘) ] [(‘name‘, ‘score‘), (‘name‘, ‘score‘), (‘name‘, ‘score‘)] # 方式三:可直接按照KEY找到目标信息 时间复杂度为O(1) { ‘zhangsan‘:{‘score‘:‘xxx‘}, ‘lisi‘:{‘score‘:‘xxx‘} } {‘zhangsan‘: {‘score‘: ‘xxx‘}, ‘lisi‘: {‘score‘: ‘xxx‘}}
原文:https://www.cnblogs.com/linranran/p/13441639.html