Python split a list into n groups in all possible combinations of group length and elements within group
<p>I want to split a list into n groups in all possible combinations (allowing for variable group length). </p>

<p>Say, I have the following list:</p>

<pre><code>lst=[1,2,3,4]
</code></pre>

<p>If I specify n=2, the list could be divided either into groups of 1 element-3 elements or 2 elements-2 elements. Within those two ways of splitting the list, there are unique combinations of which elements go in each list. </p>

<p>With n=2, these would be:</p>

<pre><code>(1),(2,3,4)
(2),(1,3,4)
(3),(1,2,4)
(4),(1,2,3)
(1,2),(3,4)
(1,3),(2,4)
(1,4),(2,3)
</code></pre>

<p>With n=1 these would be:</p>

<pre><code>(1,2,3,4)
</code></pre>

<p>And with n=3 these would be:</p>

<pre><code>(1),(2),(3,4)
(1),(3),(2,4)
(1),(4),(2,3)
(2),(3),(1,4)
(2),(4),(1,3)
(3),(4),(1,2)
</code></pre>

<p>I am not interested in groups of length 0, and order within a group does not matter.</p>

<p>I found two similar questions, but they don't answer my question exactly.</p>

<p><a href="http://stackoverflow.com/questions/5360220/how-to-split-a-list-into-pairs-in-all-possible-ways">This</a> question splits a list into all combinations where each group is of length n (I found the answer by @tokland) to be particularly useful). However, I am not looking for all groups to be of the same length. </p>

<p>And then the first step of <a href="http://stackoverflow.com/questions/9088321/show-all-possible-groupings-of-a-list-given-only-the-amount-of-sublists-length">this</a> question gets unique combinations of split locations to split a list into n groups. However, list order is preserved here and unique combinations of elements within these groups is not determined.</p>

<p>I am looking for a combination of these two questions - a list is split into n groups in all possible combinations of group length as well as combinations of elements within a group.</p>

<p>We can use the basic recursive algorithm from <a href="http://stackoverflow.com/a/30134039">this answer</a> and modify it to produce partitions of a particular length without having to generate and filter out unwanted partitions. </p>

<pre><code>def sorted_k_partitions(seq, k):
    """Returns a list of all unique k-partitions of `seq`.

    Each partition is a list of parts, and each part is a tuple.

    The parts in each individual partition will be sorted in shortlex
    order (i.e., by length first, then lexicographically).

    The overall list of partitions will then be sorted by the length
    of their first part, the length of their second part, ...,
    the length of their last part, and then lexicographically.
    """
    n = len(seq)
    groups = []  # a list of lists, currently empty

    def generate_partitions(i):
        if i &gt;= n:
            yield list(map(tuple, groups))
        else:
            if n - i &gt; k - len(groups):
                for group in groups:
                    group.append(seq[i])
                    yield from generate_partitions(i + 1)
                    group.pop()

            if len(groups) &lt; k:
                groups.append([seq[i]])
                yield from generate_partitions(i + 1)
                groups.pop()

    result = generate_partitions(0)

    # Sort the parts in each partition in shortlex order
    result = [sorted(ps, key = lambda p: (len(p), p)) for ps in result]
    # Sort partitions by the length of each part, then lexicographically.
    result = sorted(result, key = lambda ps: (*map(len, ps), ps))

    return result
</code></pre>

<p>There's quite a lot going on here, so let me explain. </p>

<p>First, we start with a procedural, bottom-up (teminology?) implementation of the same <a href="http://stackoverflow.com/a/30134039">aforementioned recursive algorithm</a>:</p>

<pre><code>def partitions(seq):
    """-&gt; a list of all unique partitions of `seq` in no particular order.

    Each partition is a list of parts, and each part is a tuple.
    """
    n = len(seq)
    groups = []  # a list of lists, currently empty

    def generate_partitions(i):
        if i &gt;= n:
            yield list(map(tuple, groups))
        else:
            for group in groups
                group.append(seq[i])
                yield from generate_partitions(i + 1)
                group.pop()

            groups.append([seq[i]])
            yield from generate_partitions(i + 1)
            groups.pop()

    if n &gt; 0:
        return list(generate_partitions(0))
    else:
        return [[()]]
</code></pre>

<p>The main algorithm is in the nested <code>generate_partitions</code> function. Basically, it walks through the sequence, and for each item, it: 1) puts the item into each of current groups (a.k.a parts) in the working set and recurses; 2) puts the item in its own, new group. </p>

<p>When we reach the end of the sequence (<code>i == n</code>), we yield a (deep) copy of the working set that we've been building up.</p>

<p>Now, to get partitions of a particular length, we <em>could</em> simply filter or group the results for the ones we're looking for and be done with it, but this approach performs a lot of unnecessary work (i.e. recursive calls) if we just wanted partitions of some length <code>k</code>. </p>

<p>Note that in the function above, the length of a partition (i.e. the # of groups) is increased whenever:</p>

<pre><code>            # this adds a new group (or part) to the partition
            groups.append([seq[i]])
            yield from generate_partitions(i + 1)
            groups.pop()
</code></pre>

<p>...is executed. Thus, we limit the size of a partition by simply putting a guard on that block, like so:</p>

<pre><code>def partitions(seq, k):
    ...

    def generate_partitions(i):
        ...

            # only add a new group if the total number would not exceed k
            if len(groups) &lt; k:
                groups.append([seq[i]])
                yield from generate_partitions(i + 1)
                groups.pop()
</code></pre>

<p>Adding the new parameter and just that line to the <code>partitions</code> function will now cause it to only generate partitions of length <em>up to</em> <code>k</code>. This is almost what we want. The problem is that the <code>for</code> loop still sometimes generates partitions of length <em>less than</em> <code>k</code>. </p>

<p>In order to prune those recursive branches, we need to only execute the <code>for</code> loop when we can be sure that we have enough remaining elements in our sequence to expand the working set to a total of <code>k</code> groups. The number of remaining elements--or elements that haven't yet been placed into a group--is <code>n - i</code> (or <code>len(seq) - i</code>). And <code>k - len(groups)</code> is the number of new groups that we need to add to produce a valid k-partition. If <code>n - i &lt;= k - len(groups)</code>, then we <em>cannot</em> waste an item by adding it one of the current groups--we <em>must</em> create a new group. </p>

<p>So we simply add another guard, this time to the other recursive branch:</p>

<pre><code>    def generate_partitions(i):
        ...

            # only add to current groups if the number of remaining items
            # exceeds the number of required new groups.
            if n - i &gt; k - len(groups):
                for group in groups:
                    group.append(seq[i])
                    yield from generate_partitions(i + 1)
                    group.pop()

            # only add a new group if the total number would not exceed k
            if len(groups) &lt; k:
                groups.append([seq[i]])
                yield from generate_partitions(i + 1)
                groups.pop()
</code></pre>

<p>And with that, you have a working k-partition generator. You could probably collapse some of the recursive calls even further (for example, if there are 3 remaining items and we need 3 more groups, then you already know that you must split each item into their own group), but I wanted to show the function as a slight modification of the basic algorithm which generates all partitions. </p>

<p>The only thing left to do is sort the results. Unfortunately, rather than figuring out how to directly generate the partitions in the desired order (an exercise for a smarter dog), I cheated and just sorted post-generation.   </p>

<pre><code>def sorted_k_partitions(seq, k):
    ...
    result = generate_partitions(0)

    # Sort the parts in each partition in shortlex order
    result = [sorted(ps, key = lambda p: (len(p), p)) for ps in result]
    # Sort partitions by the length of each part, then lexicographically.
    result = sorted(result, key = lambda ps: (*map(len, ps), ps))

    return result
</code></pre>

<p>Somewhat self-explanatory, except for the key functions. The first one: </p>

<pre><code>key = lambda p: (len(p), p) 
</code></pre>

<p>says to sort a sequence by length, then by the sequence itself (which, in Python, are ordered lexicographically by default). The <code>p</code> stands for "part". This is used to sort the parts/groups within a partition. This key means that, for example, <code>(4,)</code> precedes <code>(1, 2, 3)</code>,  so that <code>[(1, 2, 3), (4,)]</code> is sorted as <code>[(4,), (1, 2, 3)]</code>.</p>

<pre><code>key = lambda ps: (*map(len, ps), ps) 
# or for Python versions &lt;3.5: lambda ps: tuple(map(len, ps)) + (ps,)
</code></pre>

<p>The <code>ps</code> here stands for "parts", plural. This one says to sort a sequence by the lengths of each of its elements (which must be sequence themselves), then (lexicographically) by the sequence itself. This is used to sort the partitions with respect to each other, so that, for example, <code>[(4,), (1, 2, 3)]</code> precedes <code>[(1, 2), (3, 4)]</code>. </p>

<p>The following:</p>

<pre><code>seq = [1, 2, 3, 4]

for k in 1, 2, 3, 4:
    for groups in sorted_k_partitions(seq, k):
        print(k, groups)
</code></pre>

<p>produces:</p>

<pre><code>1 [(1, 2, 3, 4)]
2 [(1,), (2, 3, 4)]
2 [(2,), (1, 3, 4)]
2 [(3,), (1, 2, 4)]
2 [(4,), (1, 2, 3)]
2 [(1, 2), (3, 4)]
2 [(1, 3), (2, 4)]
2 [(1, 4), (2, 3)]
3 [(1,), (2,), (3, 4)]
3 [(1,), (3,), (2, 4)]
3 [(1,), (4,), (2, 3)]
3 [(2,), (3,), (1, 4)]
3 [(2,), (4,), (1, 3)]
3 [(3,), (4,), (1, 2)]
4 [(1,), (2,), (3,), (4,)]
</code></pre>

python