Place n indistinguishable items into k distinguishable boxes

Arnaud Delobelle arnodel at googlemail.com
Thu Feb 28 11:57:36 EST 2008


On Feb 28, 4:44 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:

> ... here is another attempt on the same principle:
>
> ---------------
> def boxings(n, k):
>     """boxings(n, k) -> iterator
>
>     Generate all ways to place n indistiguishable items into k
>     distinguishable boxes
>     """
>     seq = [n]*k + [0]
>     while True:
>         yield tuple(seq[i] - seq[i+1] for i in xrange(k))
>         i = seq.index(0) - 1
>         if i >= 1:
>             seq[i:k] = [seq[i] - 1] * (k - i)
>         else:
>             return

Actually this is better as it handles k=0 correctly:

def boxings(n, k):
    seq, i = [n]*k + [0], k
    while i:
        yield tuple(seq[i] - seq[i+1] for i in xrange(k))
        i = seq.index(0) - 1
        seq[i:k] = [seq[i] - 1] * (k-i)

--
Arnaud




More information about the Python-list mailing list