Search code examples
pythonpermutationcombinatorics

List all combinations of 3 equally sized partitions of a list


I have a vector containing 15 values and would like to find all the possible ways to partition the vector into 3 equally sized partitions. I know there is n!/(n-r)!r! combinations to take r values out of a list of n values with replacement & this is easily generated with itertools in Python.

Does there exist an easy solution to list all combinations in this case as well?


Solution

  • Mathematically there will be n!/((n/3!)^3)/3! solutions, for example if n=15 there will be 126126 combinations and if n=6 there will be 15 combinations.

    As the task needs to remove duplicates, which is not supported by itertools, I would recommend package more_itertools:

    import more_itertools
    n = 6
    assert n%3 == 0
    
    [x for x in more_itertools.set_partitions(range(n), 3) if len(x[0]) == len(x[1]) == len(x[2])]
    
    [[[0, 1], [2, 3], [4, 5]],
     [[0, 1], [3, 4], [2, 5]],
     [[0, 1], [2, 4], [3, 5]],
     [[1, 2], [0, 3], [4, 5]],
     [[0, 2], [1, 3], [4, 5]],
     [[1, 2], [3, 4], [0, 5]],
     [[0, 2], [3, 4], [1, 5]],
     [[1, 2], [0, 4], [3, 5]],
     [[0, 2], [1, 4], [3, 5]],
     [[2, 3], [1, 4], [0, 5]],
     [[2, 3], [0, 4], [1, 5]],
     [[1, 3], [2, 4], [0, 5]],
     [[0, 3], [2, 4], [1, 5]],
     [[1, 3], [0, 4], [2, 5]],
     [[0, 3], [1, 4], [2, 5]]]