yoshegg
yoshegg

Reputation: 69

python - Concatenate list elements in every possible way

My issue might be quite difficult to explain (maybe that's also the reason I did not find a solution or a similar problem).

What I have is a list with some elements (in my specific case also lists). What I want is having every possible combinations of concatenations of this list in the same order.

For example:

[[1], [2], [3], [4]]  # what I have

{                     # what I want
    [[1], [2], [3], [4]],
    [[1, 2], [3], [4]],
    [[1], [2, 3], [4]],
    [[1], [2], [3, 4]],
    [[1, 2], [3, 4]],  # Update 1
    [[1, 2, 3], [4]],
    [[1], [2, 3, 4]],
    [[1, 2, 3, 4]]
}

In general the length of the sublists is greater then 1; also the list itself may have more than 4 elements.

Any help is highly appreciated.

UPDATE 1: added missing combination in code.

Upvotes: 0

Views: 301

Answers (1)

Tom Karzes
Tom Karzes

Reputation: 24102

Try this:

def concats(l):
    if len(l) < 2:
        return [l]

    return [[l[0]] + x for x in concats(l[1:])] + \
           concats([l[0] + l[1]] + l[2:])

Here's a sample case:

l = [[1], [2], [3], [4]]
r = concats(l)

And the result:

[[[1], [2], [3], [4]],
 [[1], [2], [3, 4]],
 [[1], [2, 3], [4]],
 [[1], [2, 3, 4]],
 [[1, 2], [3], [4]],
 [[1, 2], [3, 4]],
 [[1, 2, 3], [4]],
 [[1, 2, 3, 4]]]

Edit: It wasn't clear to me how the empty list should be handled, but in that case you may want to simply return an empty list without wrapping it in an outer list - I'll leave that case up to you. A simple check at the top of the function can handle it any way you choose (and it won't affect the larger cases).

Upvotes: 4

Related Questions