Another itertool function?

Steven Taschuk staschuk at telusplanet.net
Tue Apr 29 19:24:35 EDT 2003


Quoth Alex Martelli:
> Steven Taschuk wrote:
  [...]
> > Alexander Schmolck proposed such a function back in February [1];
> > his version included a "step" argument doing what you suggest.
> > 
> > In the discussion of whether such a function was useful enough to
> > be included in itertools, I provided several use cases [2], but
> > was unable to find a convincing one which needed a step other than
> > one.  Do you have one in mind?
> 
> Simplest example: I have a flat sequence k1 v1 k2 v3 k3 v3 ... and I
> want a mapping k1->v1, k2->v2 etc.  dict(windowed(x, 2, 2)) would do it.

Ah, yes.  Sorry, I should have mentioned the case step = window
size, which I agree is important.  In Schmolck's original
proposal, that case even has its own function, xgroup.

> Second example: if I have a sequence of daily earnings and I want a "moving 
> daily average" -- for each day, the average of the seven days centered on
> it -- imap(sum, windowed(earnings, 7)) would suffice [ok, sum is not the
> same as avg, but dividing each number by 7 ain't hard if needed].  But say
> I want a "moving weekly average" instead -- for each WEEK, the average
> (or sum) of the three weeks centered on it.  Why not:
> imap(sum, windowed(earnings, 21, 7)) -- it seems simplest. Or maybe faster:
> imap(sum, windowed(imap(sum, windowed(earnings, 7, 7)), 3)).

With xgroup at hand, I feel xwindow(xgroup(earnings, 7), 3) is
clearer in this case than xwindow(earnings, 21, 7).  In full:

    def avg(x):
        return sum(x)/len(x)
    weeklyearnings = imap(sum, xgroup(earnings, 7))
    movavg = imap(avg, xwindow(weeklyearnings, 3))

(Imho: if you want a 3-week moving average, write one; don't write
a 21-day moving average that skips six out of seven days.)

> In general, 1 and N are going to be the most popular 'steps' for a
> window of length N, but other values may help for moving averages &c.

Agreed that 1 and n would be most common.  If there's no use case
for other values, I feel having a step argument in xwindow is a
premature generalization.  (Note that it can be added easily
later, if use cases surface.)

-- 
Steven Taschuk                          staschuk at telusplanet.net
"Its force is immeasurable.  Even Computer cannot determine it."
                           -- _Space: 1999_ episode "Black Sun"





More information about the Python-list mailing list