diff options
author | Raymond Hettinger <python@rcn.com> | 2010-01-24 03:34:56 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2010-01-24 03:34:56 (GMT) |
commit | cef40c34a9d93c31e390d9b94ad665a22c0951c3 (patch) | |
tree | e7ae2431cf672b649087a60e1ed1b241060ee64c | |
parent | 495517cd38cf655e23cc70ba04b9085619c6a04a (diff) | |
download | cpython-cef40c34a9d93c31e390d9b94ad665a22c0951c3.zip cpython-cef40c34a9d93c31e390d9b94ad665a22c0951c3.tar.gz cpython-cef40c34a9d93c31e390d9b94ad665a22c0951c3.tar.bz2 |
Issue 7764: Improve recipe for itertools.consume().
-rw-r--r-- | Doc/library/itertools.rst | 15 |
1 files changed, 14 insertions, 1 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 229bc1f..250c842 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -641,7 +641,13 @@ which incur interpreter overhead. def consume(iterator, n): "Advance the iterator n-steps ahead. If n is none, consume entirely." - collections.deque(islice(iterator, n), maxlen=0) + # The technique uses objects that consume iterators at C speed. + if n is None: + # feed the entire iterator into a zero-length deque + collections.deque(iterator, maxlen=0) + else: + # advance to the emtpy slice starting at position n + next(islice(iterator, n, n), None) def nth(iterable, n, default=None): "Returns the nth item or a default value" @@ -751,3 +757,10 @@ which incur interpreter overhead. # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B # unique_justseen('ABBCcAD', str.lower) --> A B C A D return imap(next, imap(itemgetter(1), groupby(iterable, key))) + +Note, many of the above recipes can be optimized by replacing global lookups +with local variables defined as default values. For example, the +*dotproduct* recipe can be written as: + + def dotproduct(vec1, vec2, sum=sum, imap=imap, mul=operator.mul): + return sum(imap(mul, vec1, vec2)) |