Enumerating k-segmentations of a sequence

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Nov 25 18:53:35 CET 2008


My version:

from itertools import combinations as xcombinations
from itertools import izip, islice

def xpairwise(iterable):
    # docs and doctests removed
    return izip(iterable, islice(iterable, 1, None))

def segmentations(seq, k):
    for comb in xcombinations(range(1, len(seq)), k-1):
        yield [seq[start:stop] for start,stop in xpairwise((None,) +
comb + (None,))]

for seg in segmentations(range(1, 6), 3):
    print seg
print

for seg in segmentations(range(1, 7), 2):
    print seg
print

for seg in segmentations(range(1, 7), 3):
    print seg
print

for seg in segmentations(range(1, 7), 4):
    print seg
print

Other people have already explained how this works.

Bye,
bearophile



More information about the Python-list mailing list