Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over partitions in Python

I was wondering what the best way is (in Python) to iterate over partitions of a list of a given size.

Say, for example, we have the list [1,2,3,4,5] and we want k=3 partitions. A poor way of doing this would be to write:

lst = [1,2,3,4,5]
for i in range(1,len(lst)):
    for j in range(i+1, len(lst)):
        print lst[:i], lst[i:j], lst[j:]

This gives

[1], [2], [3,4,5]
[1], [2,3], [4,5]
...
[1,2,3], [4], [5]

But if I later wanted to iterate over k=4 partitions, then I would have to add a level of for loop nesting, which can't be done at runtime. Ideally, I'd like to write something like:

for part in partitions([1,2,3,4,5], k):
    print part

Does anyone know the best way of doing this?

like image 333
Alex Reinking Avatar asked May 11 '14 19:05

Alex Reinking


1 Answers

I would use the same idea as yours without pairwise:

from itertools import combinations

def partitions(items, k):

    def split(indices):
        i=0
        for j in indices:
            yield items[i:j]
            i = j
        yield items[i:]

    for indices in combinations(range(1, len(items)), k-1):
        yield list(split(indices))
like image 163
Kiwi Avatar answered Sep 28 '22 23:09

Kiwi