iterator? way of generating all possible combinations?

Diez B. Roggisch deets at nospam.web.de
Tue May 30 13:35:33 EDT 2006


akameswaran at gmail.com wrote:

> 
> 
> Well thanks for the mathematical restatement of my problem.  I had
> forgotten the proper terms.  Searching on those terms generates some
> interesting results.
> 
> However, none of the algo's I have checked will work with generated
> sequences, or iterable classes, as posited in my first post.
> 
> While appropriate to the current domain, ie dice.  What if you want
> combinations of extrememely large lists, say 3 sets of 10 mil items.
> In such a case, I really do want my sets to be generators rather than
> lists or set objects.
> 
> This is what had me stumped before, and still has me stumped.

def combinations(l, depth):
    if depth == 1:
       for element in l:
           yield (element,)
    else:
        for element in l:
            for rest in combinations(l, depth -1 ):
                yield (element,) + rest

HTH,

Diez



More information about the Python-list mailing list