On Sat, Dec 14, 2019 at 3:56 PM David Mertz <me...@gnosis.cx> wrote: > [...] compositions are simply the permutations on the full length of the > list of each partition. >
Using permutations of partitions would be overkill. For compositions of a given fixed length, it's much easier to compute them directly using a stars-and-bars approach. The OP is simply asking for all possible placements of `m-1` "dividers" in the input string `s`, and those divider positions can be computed directly using `itertools.combinations(range(1, len(s)), m-1)`. That gives the following one-liner: segment = lambda s, m: (tuple(s[i:j] for i, j in zip((0,)+c, c+(len(s),))) for c in itertools.combinations(range(1, len(s)), m-1)) Example output is exactly as the OP requested: >>> list(segment("12345", m=3)) [('1', '2', '345'), ('1', '23', '45'), ('1', '234', '5'), ('12', '3', '45'), ('12', '34', '5'), ('123', '4', '5')] -- Mark
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/YGKXAHSNU3QUYPSW2YASALY22WUR4WKN/ Code of Conduct: http://python.org/psf/codeofconduct/