Created
July 3, 2012 09:32
-
-
Save mattalcock/3038746 to your computer and use it in GitHub Desktop.
Single pass stats with generators in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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