Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A more efficient Benford's Law code?

Tags:

python-2.7

An academic question. This function computes Benford's Law for integers up to maxvalue, and prints a summary table. I've tried a nested for-loop method, a dict method, and this collections method. The latter (code below) seems the fastest (timeit result: 1.4852424694 sec), but is there a faster and memory-efficient method for cycling through so many possibilities?

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)+' %']))
like image 242
ksed Avatar asked Jul 17 '26 02:07

ksed


1 Answers

Changing the main loop to this:

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

takes the time from about 1.55s to about 1.25; however taking out the **2 takes the time down to about 0.32s.

In other words, the vast majority of your time is spent squaring your operands.

Curiously, I was able to shave about 0.05s by using "%s" % ((i+1)**2) instead of str((i+1)**2).

like image 70
Gabe Avatar answered Jul 22 '26 19:07

Gabe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!