Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Single pass stats with generators in Python
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment