【发布时间】:2020-07-20 06:40:43
【问题描述】:
我是渐近分析概念的新手。我正在阅读 Goodrich 的“Python 中的数据结构和算法”。在那本书中,它的实现如下:
def prefix average2(S):
”””Return list such that, for all j, A[j] equals average of S[0], ..., S[j].”””
n = len(S)
A = [0] n # create new list of n zeros
for j in range(n):
A[j] = sum(S[0:j+1]) / (j+1) # record the average
return A
这本书说这段代码在 O(n^2) 中运行,但我不知道如何。 S[0:j+1] 在 O(j+1) 时间内运行,但我们如何知道“sum()”在什么时间运行以及如何让运行时间为 O(n^2)?
【问题讨论】:
-
sum(list)对列表的 所有 个元素求和,因此对于 m 个元素来说是 O(m),因为您显然必须“访问”每个元素一次才能对它们求和起来。
标签: python algorithm performance big-o