Fatest standard way to sum bytes (and their squares)?

Erik Max Francis max at alcyone.com
Mon Aug 13 04:25:19 CEST 2007

Duncan Booth wrote:

> I haven't timed it, but at the very least I'd avoid going through all the 
> data twice:
> count = {}
> for i in range(256):
>   count[chr(i)] = 0
> for x in data:
>   count[x] += 1
> ordinalSum = sum(ord(c)*count[c] for c in count)
> ordinalSumSquared = sum(ord(c)**2 * count[c] for c in count)

This approach is definitely faster than using a generator in my tests, 
and was second fastest overall.  I'm actually a bit surprised that it's 
as fast as it is; it never would have occurred to me to try it this way.

Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   It is morale that wins the victory.
    -- Gen. George C. Marshall

More information about the Python-list mailing list