一个学术问题。此函数计算 Benford's Law对于最大值的整数,并打印汇总表。我试过嵌套的 for 循环方法、字典方法和这个集合方法。后者(下面的代码)似乎是最快的(timeit 结果:1.4852424694 秒),但是是否有一种更快且内存效率更高的方法来循环遍历这么多可能性?
from __future__ import print_function
def BenfordsLaw4(maxvalue = 10**6):
from collections import Counter
sqList = (str((i+1)**2)[0] for i in range(maxvalue))
BenfordList = Counter(sqList)
print("Benford's Law for numbers between 1 and", maxvalue, "\nDigits,\t\t\t", "Count,\t\t\t", "Percentage")
for i,j in sorted(BenfordList.iteritems()):
print(',\t\t\t\t'.join([str(i), str(j), str(j*100./maxvalue)+' %']))
最佳答案
将主循环更改为:
def BenfordsLaw4(maxvalue = 10**6):
BenfordList = {str(i+1):0 for i in range(9)}
for i in (str((i+1)**2)[0] for i in xrange(maxvalue)):
BenfordList[i] += 1
耗时从1.55s左右到1.25s左右;然而取出 **2
将时间减少到大约 0.32 秒。
换句话说,您的大部分时间都花在计算操作数的平方上。
奇怪的是,通过使用 "%s"% ((i+1)**2)
而不是 str((i+1)* 我能够缩短大约 0.05s *2)
.
关于python-2.7 - 更高效的本福德定律代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16797162/