[docs] Better roundrobin itertools recipe, IMHO
David Lindquist
dlindquist at google.com
Fri Feb 21 04:29:40 CET 2014
Greetings!
I recently perused the documentation for the itertools module (
http://docs.python.org/2/library/itertools.html), and attempted to
understand the examples in the Recipes section.
The roundrobin example was particularly vexing me, so I set out to code up
an alternative that was more clear and concise. I believe I succeeded and
wondered if my code might be a better example for the documentation (with
due respect to George Sakkis!).
Not only is it fewer lines, it is more straightforward and idiomatic, I
think. Plus, it's more than twice as fast to boot (on my machine at least,
according to timeit):
from itertools import *
def roundrobin(*iterables):
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
sentinel = object()
it = chain.from_iterable(izip_longest(fillvalue=sentinel, *iterables))
return (i for i in it if i is not sentinel)
if __name__ == '__main__':
import timeit
print(timeit.timeit("list(roundrobin('ABC', 'D', 'EF'))",
setup="from __main__ import roundrobin"))
A typical result from timeit:
$ python roundrobin_mine.py
5.45610809326
$ python roundrobin_from_docs.py
13.8604800701
What do you think? Might this version supplant the current one in the
documentation?
Cheers,
David Lindquist
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/docs/attachments/20140220/43e2fc82/attachment.html>
More information about the docs
mailing list