我试图计算下一个函数max_list11
的时间复杂度,该函数递归地查找列表的最大值:
def max11(L,left,right):
if left==right:
return L[left]
return max(L[left], max11(L,left+1,right))
def max_list11(L):
return max11(L,0,len(L)-1)
从我发现的情况来看,时间复杂度应该是O(n)
,因为函数所做的是n
乘以2个对象列表的最大值,尽管当我计算运行时间时,我得到了运行时间的多项式增长(显然是O(n²)
),我想知道这是为什么。你知道吗
我用这种方法计算函数的时间:
def elasped(f,L):
t0 = time.clock()
s = f(L)
return(time.clock()-t0)
def avg_elasped(f,L,times = 100):
measurements = []
for i in range(times):
measurements += [elasped(f,L)]
return sum(measurements)/times
然后我试了1000,2000。。。。,10000个长列表。你知道吗
递归方法将每次调用的输入大小减少一个,因此理论上是线性的(因为实际上是线性搜索最大值)。Python列表的实现将扭曲基于计时器的分析。你知道吗
它是线性的:
始终使用
timeit.default_timer()
作为时间戳。或者像我对这个输出所做的那样。time.clock()
根据您的操作系统有不同的含义。从docs:相关问题 更多 >
编程相关推荐