[Python-ideas] Rewriting the "roundrobin" recipe in the itertools documentation

Wes Turner wes.turner at gmail.com
Tue Nov 21 21:11:23 EST 2017


Here's toolz.itertoolz.interleave():

def interleave(seqs):
    """ Interleave a sequence of sequences
    >>> list(interleave([[1, 2], [3, 4]]))
    [1, 3, 2, 4]
    >>> ''.join(interleave(('ABC', 'XY')))
    'AXBYC'
    Both the individual sequences and the sequence of sequences may be
infinite
    Returns a lazy iterator
    """
    iters = itertools.cycle(map(iter, seqs))
    while True:
        try:
            for itr in iters:
                yield next(itr)
            return
        except StopIteration:
            predicate = partial(operator.is_not, itr)
            iters = itertools.cycle(itertools.takewhile(predicate, iters))

At first glance, map should be e.g. six.moves.map for pythonic backward
compatibility.

Is this slower than the linear time implementations listed here?

On Tuesday, November 21, 2017, Alon Snir <AlonSnir at hotmail.com> wrote:

> def roundrobin(*iterables):
>     "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
>     nexts = [ iter(it).__next__ for it in iterables ]
>     i = 0
>     while nexts:
>         i %= len(nexts)
>         try:
>             yield nexts[i]()
>         except StopIteration:
>             del nexts[i]
>         else:
>             i += 1
>
> Regards
> Alon Snir
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org <javascript:;>
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171121/3ed0923f/attachment.html>


More information about the Python-ideas mailing list