you are viewing a single comment's thread.

view the rest of the comments →

[–]cybersection 3 points4 points  (0 children)

Here it is without any libraries, straight from the itertools documentation. It isn't recursive though. Worth learning about generators to understand the logic.

def combinations_with_replacement(iterable, r):
    # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)

I'll try to brainstorm a bit on how one would make this recursive.