subset permutations

Gerard Flanagan grflanagan at yahoo.co.uk
Sat Dec 10 07:06:38 EST 2005


Jay Parlar wrote:

> On Dec 8, 2005, at 5:29 PM, dgspambot at gmail.com wrote:
> >
> > Hello all,
> >
> > I'm a beginner with programming. Trying to teach myself with that
> > excellent rat book. Unfortunately I just can't seem to figure out a
> > simple problem that has come up at my work (biology lab):
> > let's say I have a list
> > ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V
> > ','W','Y'] . I need to generate permutations of this list. I have
> > found plenty of code on the web to generate ALL possible permutations.
> > What I need are all possible 4-letter permutations. I cannot seem to
> > figure out how to modify Mike Davie's permutation generator
> > http://www.bigbold.com/snippets/posts/show/753 to acheive this. Any
> > help would be appreciated.
> >
>


The 'kSubsets' function here:

    http://www.gflanagan.net/site/python/05/kSubsetGenerator.html

should give you the combinations, though how well it does so is another
matter. (Only tested roughly). Then:

>>>import string
>>>choice = string.letters[26:]
>>>combinations = list(kSubsets(choice,4))
>>>print combinations

To get the permutations(no repeats) you can just permute each
combination, for which the Permutation class here:

    http://www.gflanagan.net/site/python/05/Johnson.html

might help. Eg.

>>> def kPerms( alist, k ):
... 	n = len(alist)
... 	for vector in nkRange(n,k):
... 		for perm in Permutation(vector):
... 			ret = []
... 			for i in perm:
... 				ret.append( alist[i-1] )
... 			yield ret
... 			
>>> x = list( kPerms(choice, 3) )
>>> print x

Gerard




More information about the Python-list mailing list