python-2.7 - 更高效的本福德定律代码?

标签 python-2.7

一个学术问题。此函数计算 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/

相关文章:

python - BNF 文法符号拆分的正则表达式

python - TemplateDoesNotExist 位于/index.html

python-2.7 - pyqtgraph删除pyqt4 gui中的持久图例

python - python中<>和!=有什么区别

python - 如何实际下载附件?

python - 为什么属性包装的成员列表显示意外的值?

python-2.7 - python list.append() - 不一致的输出

python - 当我在 Python 中使用 open(filename) 或在 C 中使用 fopen(filename) 时,保存文件的编码是什么?

python - 将表达式作为命名参数名称传递

Python 2.7 和 GCP 谷歌 BigQuery : Capturing file load errors?