As stated in the title, I'm trying to generate all partitions of a set of size n where all the subsets have size 2, and if n is uneven, there is ne singleton set. I very slightly modified some SO code for generating all partitions to get this:
def partitionIntoPairs(collection):
if len(collection) == 1:
yield [ collection ]
return
first = collection[0]
for smaller in partition2(collection[1:]):
for n, subset in enumerate(smaller):
if len(subset):
yield smaller[:n] + [[ first ] + subset] + smaller[n+1:]
yield [ [ first ] ] + smaller
This works, but is sadly far too slow. My second idea is to generate all pairs for a certain set using itertools.combinations, and then recursively call the function for every det without a given pair removed, but I'm guessing that's even slower. Also the implmentation is incorrect, it only returns one possible paritition, and I am unsure how to get it to return all of them:
from itertools import combinations
def partitionIntoPairs2(collection):
if not collection:
return []
elif len(collection) == 1:
return [(next(iter(collection)))]
else:
pairs = set(combinations(collection, 2))
for pair in pairs:
collection.remove(pair[0])
collection.remove(pair[1])
return partition3(collection) + [pair]
I stumbled upon some algorithms for partitions with a given number of sets, and various implementations of algorithms generating all possible partitions, but neither of those efficiently solve my problem as far as I can see.
So, to formulate a more concrete question: If the second algorithm is a viable option, what would be the correct implementation? And of course, is there a faster way to do this? If yes, how?