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] an
I accomplished what I was trying to do by writing:
from itertools import tee, izip, combinations
def partitions(items, k):
N = len(items)
def pairwise(iterable): # Taken from itertools recipies
a, b = tee(iterable)
next(b, None)
return izip(a, b)
def applyPart(part, items):
lists = []
for l,h in pairwise([0] + part + [N]):
lists.append(items[l:h])
return lists
for part in combinations(range(1, N), k - 1):
yield applyPart(list(part), items)