Generating all possible combination of elements in a list

Mir Nazim mirnazim at gmail.com
Mon Jul 24 06:11:07 EDT 2006


Martin v. Löwis wrote:
> 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?

condition are there cannot be more than 3 consecutive 2's or 1's

> 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).
>

Yes that number I had already worked out and it is 792 for second list.
Now I have generated all distinct permutations and after eliminating
the permutations based on above condition I am left with 1060
permutations.

Now I ahave a lits with 1060 lists in it. Now comes the hard part.
How many possible distinct ways are there to arrange 1060 elements
taken 96 at a time

1060! / (1060 - 96)!


Hope you got the idea, why i need some faster ways to do it.
Now out of these i need to test only those lists whose sum of
elements(18 or 19) follows a particular pattern.

Can Anybody can alternate ways to do it on a Celeron 1.4 Ghz, 256 MB
RAM laptop.

Thnaks

> 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