一个学术问题。此函数计算最大最大值的整数的 Benford 定律,并打印一个汇总表。我尝试过嵌套的 for 循环方法、dict 方法和这个 collections 方法。后者(下面的代码)似乎是最快的(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)+' %']))