Creating combination of sequences

Josiah Carlson jcarlson at uci.edu
Sat Nov 13 16:00:54 EST 2004


"Mike C. Fletcher" <mcfletch at rogers.com> wrote:
> 
> Minho Chae wrote:
> 
> >Hello, python lovers!!
> >
> >I'm trying to create combinations of sequences.
> >  
> >
> A simple recursive generator should produce what you want while being 
> fairly easy to read...
> 
>  >>> def permute( choices, length=8 ):
> ...     if length > 1:
> ...         for suffix in permute(choices,length-1):
> ...             for choice in choices:
> ...                 yield choice + suffix
> ...     else:
> ...         for choice in choices:
> ...             yield choice
> 
> That's not the same ordering you wanted, but that's merely a matter of 
> swapping the order of choice and suffix.

Or even the better non-recursive 'base-k' version...

Note that a permutation is just a reordering of the set of elements that
one has.  There are only n! number of permutations of any arbitrary
sequence (assuming the n items are unique).

I can't remember the mathematical name of what the OP wanted (because my
brain is dumb today).


def blah(choices, length, force_string=0):
    lch = len(choices)
    length = long(length)
    if lch <= 0:
        raise ValueError, "choices must be a sequence of at least 1 item"
    if length <= 0:
        raise ValueError, "length must be an integer >= 1"
    #use longs and a while loop because we may be dealing with sequences
    #>= 2**31 in size, and we may be using Python < 2.4
    cur = 0L
    m = lch**length
    while cur < m:
        l = [choices[(cur//(lch**i))%lch] for i in xrange(length-1, -1, -1)]
        if force_string:
            yield ''.join(map(str, l))
        else:
            yield l
        cur += 1

>>> for i in blah('atcg', 2, 1):
...     print i
...
aa
at
ac
ag
ta
tt
tc
tg
ca
ct
cc
cg
ga
gt
gc
gg
>>> 


 - Josiah




More information about the Python-list mailing list