Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Place n indistinguishable items into k distinguishable boxes

Reply
Thread Tools

Place n indistinguishable items into k distinguishable boxes

 
 
Arnaud Delobelle
Guest
Posts: n/a
 
      02-28-2008
On Feb 28, 4:44*pm, Arnaud Delobelle <(E-Mail Removed)> 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

 
Reply With Quote
 
 
 
 
castironpi@gmail.com
Guest
Posts: n/a
 
      02-28-2008
On Feb 28, 10:07*am, Mark Dickinson <(E-Mail Removed)> wrote:
> On Feb 28, 5:02*am, Michael Robertson <(E-Mail Removed)> wrote:
>
> > 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[i] 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.)
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Space between input boxes and selection boxes is not the same in Internet Explorer Stefan Mueller HTML 5 06-16-2009 02:06 PM
resolve single line with multiple items into mutliple lines, single items ela Perl Misc 12 04-06-2009 06:47 PM
Taskbar - Past Items back into Current Items Moke Gibboni Computer Support 5 10-29-2008 05:26 PM
unable to retrieve listbox items on postback , items moved usingjavascript between 2 list boxes (source and target ) divya ASP .Net 1 05-28-2008 05:27 AM
help, black dogs face indistinguishable lucky1 Digital Photography 22 03-25-2005 12:00 AM



Advertisments