[Python] media di un generatore
Marco Beri
marcoberi a gmail.com
Mer 11 Dic 2013 09:11:55 CET
Qualche prova in pių:
import itertools
def gen(n):
i = 1
while i < n:
yield i
i += 1
def avg1():
n, sum_ = 0, 0.0
for v in gen(100000):
sum_ += v
n += 1
return sum_ / n
def avg2():
tot = 0.0
for n, v in enumerate(gen(100000), 1):
tot += v
try:
return tot / n
except UnboundLocalError:
return 0 # ???
def avg3():
x = itertools.izip(*((i, 1) for i in gen(100000)))
return float(sum(x.next())) / sum(x.next())
def avg4():
it1, it2 = itertools.tee(gen(100000))
try:
return sum(it1) / float(sum(1 for _ in it2))
except ZeroDivisionError:
return 0 # ???
if __name__ == '__main__':
import timeit
for s in range(1, 5):
f = "avg%s" % s
print f, timeit.timeit(f + "()", setup="from __main__ import %s" %
f, number=100)
*avg1 2.8069589138*
*avg2 2.88984298706*
*avg3 6.68095088005*
*avg4 2.85471391678*
Postmettendo che avg1 e avg3 nel caso di sequenza nulla sbagliano.
Ciao.
Marco.
-------------- parte successiva --------------
Un allegato HTML č stato rimosso...
URL: <http://lists.python.it/pipermail/python/attachments/20131211/5ef4b47b/attachment.html>
Maggiori informazioni sulla lista
Python