[Peter Otten] > from __future__ import division > > from itertools import islice, tee, izip . . . > def moving_average2(items, n): > first_items, last_items = tee(items) > accu = sum(islice(last_items, n-1)) > for first, last in izip(first_items, last_items): > accu += last > yield accu/n > accu -= first > > While moving_average1() is even slower than your inefficient variant, > moving_average2() seems to be a tad faster than the efficient one.
This is nicely done and scales-up well. Given an n-average of m-items, it has O(n) memory consumption and O(m) running time. In contrast, the other variants do more work than necessary by pulling the whole sequence into memory or by re-summing all n items at every step, resulting in O(m) memory consumption and O(m*n) running time. This recipe gets my vote for the best solution. Raymond -- http://mail.python.org/mailman/listinfo/python-list