[Python-ideas] Include partitioning in itertools
Serhiy Storchaka
storchaka at gmail.com
Sun Nov 1 13:10:08 EST 2015
On 01.11.15 13:08, Albert ten Oever wrote:
> I really hope this isn't proposed before - I couldn't find anything in
> the archives.
>
> I want to propose to include a 'partition' (mathematically more correct:
> a set partition) function in itertools. To my knowledge, partitioning of
> a set (iterable) is quite a common thing to do and a logic extension of
> the combinatoric generators in itertools.
>
> It is implemented as a Python recipe
> (http://code.activestate.com/recipes/576795-partitioning-a-sequence/). I
> found that implementing a partition generator of an iterable isn't very
> straightforward, which, in my opinion, strengthens the case for
> implementing it as a separate function.
The implementation can be simpler and don't require itertools:
def partition(seq):
if seq:
yield [seq]
for i in range(1, len(seq)):
s = seq[i:]
for p in partition(seq[:i]):
p.append(s)
yield p
>>> from pprint import pprint
>>> pprint(sorted(partition('abcde'), key=len))
[['abcde'],
['a', 'bcde'],
['ab', 'cde'],
['abc', 'de'],
['abcd', 'e'],
['a', 'b', 'cde'],
['a', 'bc', 'de'],
['ab', 'c', 'de'],
['a', 'bcd', 'e'],
['ab', 'cd', 'e'],
['abc', 'd', 'e'],
['a', 'b', 'c', 'de'],
['a', 'b', 'cd', 'e'],
['a', 'bc', 'd', 'e'],
['ab', 'c', 'd', 'e'],
['a', 'b', 'c', 'd', 'e']]
More information about the Python-ideas
mailing list