help with code for combinations/permutations

Alex Martelli aleaxit at yahoo.com
Sat Jan 20 07:32:03 EST 2001


<cpsoct at my-deja.com> wrote in message news:94bbev$vai$1 at nnrp1.deja.com...
> It is not my question, but if i may be permitted, i think i can ask get
> more specific. Or rather try to suggest one possibility. Do you perhaps
> mean something that would be like this:
>
> permute(list, n) -- return the nth permutation of a list.

Actually, the original poster explicitly asked for *combinations*, NOT
*permutations*:

> > > I need to come up with all possible combinations of the numbers

and went on to use a commutative operator ('+') on the subsets, so
I see no reason to doubt he really wanted combinations (the difference
being that ordering of items does not distinguish combinations, while
it is all that distinguishes permutations!-).

I answered the original question, in practice, exactly by building a
function that returns the N-th subset (combination) of a sequence --
easy, given the isomorphism between such subsets and binary
numbers of len(sequence) bits!-)  Enumerating permutations is
not quite as easy, although of course quite feasible.  But anyway,
the little Pythonish trick around this is writing this function as the
__getitem__ method of a class wrapped around the sequence --
that way, client-code can just loop on all 'items' (whether they be
combinations, permutations, whatever) with a for statement.


Alex






More information about the Python-list mailing list