I\'m doing some statistics work, I have a (large) collection of random numbers to compute the mean of, I\'d like to work with generators, because I just need to compute the
def my_mean(values):
total = 0
for n, v in enumerate(values, 1):
total += v
return total / n
print my_mean(X)
print my_mean(Y)
There is statistics.mean() in Python 3.4 but it calls list() on the input:
def mean(data):
if iter(data) is data:
data = list(data)
n = len(data)
if n < 1:
raise StatisticsError('mean requires at least one data point')
return _sum(data)/n
where _sum()
returns an accurate sum (math.fsum()-like function that in addition to float
also supports Fraction
, Decimal
).