1def moving_average(iterable, n=3):
2 # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
3 # http://en.wikipedia.org/wiki/Moving_average
4 it = iter(iterable)
5 d = deque(itertools.islice(it, n-1))
6 d.appendleft(0)
7 s = sum(d)
8 for elem in it:
9 s += elem - d.popleft()
10 d.append(elem)
11 yield s / float(n)
12