Python itertools round robin without duplication

I managed to change the roundrobin recipe to https://docs.python.org/3.1/library/itertools.html
enable the limit (stop when X elements are reached) - the code is below ...

Now, what I really want is "stops when elements X are reached, but without duplicating elements."
Is it possible? (because it's a generator ...)

def roundrobin(limit, *iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
                limit -= 1
                if limit == 0:
                    return

        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

calling him:

candidates = [['111', '222', '333'],['444','222','555']] 
list(roundrobin(4, *candidates))

I would like to get:

['111,'444','222','333']

and not:

['111,'444','222','222']

how do i get with current code

0
source share
1 answer

- set seen, , yield ed. , , iterable ( ), roundrobin.

def roundrobin_limited_nodupe(limit, *iterables):
    """A round-robin iterator duplicates removed and a limit.

        >>> list(roundrobin_limited_nodupe(6, 'ABC', 'DB', 'EFG'))
        ['A', 'D', 'E', 'B', 'F', 'C']  # only six elements, only one 'B'

    Notes:
      - Recipe credited to George Sakkis

    """
    pending = len(iterables)
    seen = set()  # keep track of what we've seen
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                candidate = next()
                if candidate not in seen:  # only yield when it new
                    seen.add(candidate)
                    yield candidate
                    limit -= 1
                    if limit == 0:
                        return
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))
+1

All Articles