[docs] Better roundrobin itertools recipe, IMHO
dlindquist at google.com
Fri Feb 21 04:29:40 CET 2014
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 *
"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__':
print(timeit.timeit("list(roundrobin('ABC', 'D', 'EF'))",
setup="from __main__ import roundrobin"))
A typical result from timeit:
$ python roundrobin_mine.py
$ python roundrobin_from_docs.py
What do you think? Might this version supplant the current one in the
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the docs