
clp2 at rebertia
Nov 18, 2009, 6:42 PM
Post #3 of 5
(219 views)
Permalink
|
|
Re: combinatorics via __future__ generators
[In reply to]
|
|
On Wed, Nov 18, 2009 at 4:58 PM, Phlip <phlip2005 [at] gmail> wrote: > Python: > > I have a quaint combinatorics problem. Before I solve it, or find a > solution among "generators", I thought y'all might like to show off > any solutions. > > Given an array like this... > > Â [0, 4, 3] > > Produce an array like this: > > Â [ > Â Â [0, 0, 0], > Â Â [0, 1, 0], > Â Â [0, 2, 0], > Â Â [0, 3, 0], > Â Â [0, 1, 1], > Â Â [0, 2, 1], > Â Â [0, 3, 1], > Â Â [0, 1, 2], > Â Â [0, 2, 2], > Â Â [0, 3, 2], > ] > > The first array is the counts of options in 4 slots, and the second is > all combinations of indexes of each option, such that every option > associates once with every other option. The leading 0 simply > represents a slot with no options; the algorithm must preserve those. > > This should be child's play for the generator package, right? from itertools import imap, product def special_range(n): return (xrange(n) if n else [0]) def something(arr): return product(*imap(special_range, arr)) print list(something([0,4,3])) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
|