public
Created

Single pass stats with generators in Python

  • Download Gist
gistfile1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
import random
from math import sqrt
 
def compute(gen):
def stat(x):
stat.max = x if stat.max is None else stat.max
stat.min = x if stat.min is None else stat.min
 
stat.sum += x
stat.sum2 += x*x
stat.n += 1.0
stat.max = x if x>stat.max else stat.max
stat.min = x if x<stat.min else stat.min
 
s, sum2, n = stat.sum, stat.sum2, stat.n
return n, s, s/n, sqrt(sum2/n - s*s/n/n), stat.max, stat.min
stat.sum = stat.sum2 = stat.n = 0
stat.max = stat.min = None
x = [stat(v) for v in gen][-1]
return x
 
def random_int_list(size=100, start=0, end=1000):
return (random.randrange(start,end,1) for x in xrange(size))
if __name__ == '__main__':
r = compute(random_int_list())
print r

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.