【发布时间】:2013-01-04 22:47:41
【问题描述】:
这是我使用 Python 编写的一些代码:
from math import sqrt
abundant_list = []
for i in range(12,28123+1):
dividor_list = [1]
for j in range(2, int(sqrt(i))+1):
if i%j == 0:
dividor_list.extend([i/j,j])
if sum(dividor_list) > i:
abundant_list.append(i)
print abundant_list
如您所见,代码确实在尽可能地提高效率。
如果我使用list.append 两次,或list.extend 一次,有什么区别?
我知道这可能是微小的差异,但我真的很想知道:)
【问题讨论】:
-
如果您想知道,请测量。
-
如果
extend不快于 2.appends,我会非常惊讶 -
如果我要优化它,我会使用the sieve of Eratosthenes 来查找直到
sqrt(28123)的素数,然后对于每个i,我会对其进行因式分解并使用itertools.product得到将因子组合成除数的所有方法,最后将它们相加。
标签: python list performance