Place n indistinguishable items into k distinguishable boxes

A

Arnaud Delobelle

... 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 - seq[i+1] for i in xrange(k))
        i = seq.index(0) - 1
        if i >= 1:
            seq[i:k] = [seq - 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 - seq[i+1] for i in xrange(k))
i = seq.index(0) - 1
seq[i:k] = [seq - 1] * (k-i)
 
C

castironpi

Thanks again for your efforts here.  This particular problem didn't
appear in any course I took...certainly similar problems did.

And here's the obligatory not-very-obfuscated one-liner:

from itertools import combinations as c; boxings=lambda n,k:([s[i
+1]+~s for i in range(k)] for s in [[-1]+list(t)+[n-~k] for t in
c(range(n-~k),k-1)])


This calls for an obfuscation metric, several books, and two personal
references. What is ~k doing in there twice?

(Aside: throw in an obligatority one too. Sigh.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top