Enumerating k-segmentations of a sequence
Mark Dickinson
dickinsm at gmail.com
Tue Nov 25 12:34:34 EST 2008
On Nov 25, 4:56 pm, bullockbefriending bard <kinch1... at gmail.com>
wrote:
> I'm not sure if my terminology is precise enough, but what I want to
> do is:
> [snip problem description]
> Structural Recursion not being my strong point, any ideas on how to go
> about this would be much appreciated!
If you have Python 2.6 available, itertools.combination might be
useful.
Here's an example:
from itertools import combinations
def partitions(l, k):
"""generate all partitions of a list l into k nonempty pieces"""
n = len(l)
for c in combinations(range(1, n), k-1):
c = [0] + list(c) + [n]
yield [l[c[i]:c[i+1]] for i in xrange(k)]
for p in partitions(range(1, 6), 3):
print p
Mark
More information about the Python-list
mailing list