reduce()--what is it good for? (was: Re: reduce() anomaly?)
David Eppstein
eppstein at ics.uci.edu
Tue Nov 11 17:05:54 EST 2003
In article <%Fcsb.10225$hV.422723 at news2.tin.it>,
Alex Martelli <aleaxit at yahoo.com> wrote:
> > The use of zip(seq[1:], [:-1]) to me is more obscure, and
>
> Very obscure indeed (though it's hard to say if it's _more_ obscure without
> a clear indication of what to compare it with). Particularly considering
> that it's incorrect Python syntax, and the most likely correction gives
> probably incorrect semantics, too, if I understand the task (give windows
> of 2 items, overlapping by one, on seq?).
>
> > memory/cpu-expensive in terms of creating 3 new lists.
>
> Fortunately, Hettinger's splendid itertools module, currently in Python's
> standard library, lets you perform this windowing task without creating any
> new list whatsoever.
>
> Wen seq is any iterable, all you need is izip(seq, islice(seq, 1, None)),
> and you'll be creating no new list whatsoever. Still, tradeoffs in
> obscurity (and performance for midsized lists) are quite as clear.
If I'm not mistaken, this is buggy when seq is an iterable, and you need
to do something like
seq1,seq2 = tee(seq)
izip(seq1,islice(seq2,1,None))
instead.
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
More information about the Python-list
mailing list