Generating all possible combination of elements in a list

"Martin v. Löwis" martin at v.loewis.de
Sun Jul 23 17:50:09 EDT 2006


Mir Nazim wrote:
> Example Problem:
> 
> Generate all possible permutations for
> [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
> 
> [1, 2, 1, 2, 1, 2, 2, 2, 1, 2, 1, 2] (notice an extra 2 )
> 
> eliminate some combinations based on some conditions and combine the
> rest of combinations. And now generate all possible combinations for
> resulting data set.
> Hope you get the idea.

Unfortunately, I don't. Why do you have two lists for which to generate
permutations? Why is it important that the second list has an extra 2
(actually, not extra, but it replaces a 1)?
What are "some conditions" by which to eliminate permutations?
How to "combine" the remaining permutations?
What is the "resulting data set", and what is a "possible combination"
of it?

If the task is to produce all distinct permutations of 6 occurrences
of 1 and 6 occurrences of 2, I suggest the program below. It needs
produces much fewer than 12! results (namely, 924).

Regards,
Martin

numbers = [1,2]
remaining = [None, 6, 6]
result = [None]*12

def permutations(index=0):
    if index == 12:
        yield result
    else:
        for n in numbers:
            if not remaining[n]:
                continue
            result[index] = n
            remaining[n] -= 1
            for k in permutations(index+1):
                yield k
            remaining[n] += 1

for p in permutations():
    print p



More information about the Python-list mailing list