Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all possible ordered groups in a list

Tags:

python

Given an ordered list of integers:

[1,3,7,8,9]

How can I find all the sublists that can be created from original list where order is maintained? Using the example above, I'm looking for a way to programmatically generate these sequences:

[[1],[3,7,8,9]]
[[1, 3],[7,8,9]]
[[1, 3, 7],[8,9]]
[[1, 3, 7, 8],[9]]
[[1, 3, 7, 8, 9]]
[[1, 3, 7], [8, 9]]
[[1], [3, 7], [8], [9]]
[[1], [3], [7, 8], [9]]
[[1], [3], [7], [8, 9]]
...

I'm basically looking for a way to generate all the permutations of a list where order is maintained. I can generate all the sublists where there are only 2 sublists in total using this code:

def partition(arr, idx):
    return [arr[:idx], arr[idx:]]

l = [1,3,7,8,9]
for idx in range(1, len(l)):
    groups = partition(l, idx)
    print(groups)

[[1], [3, 7, 8, 9]]
[[1, 3], [7, 8, 9]]
[[1, 3, 7], [8, 9]]
[[1, 3, 7, 8], [9]]

However, this code snippets only splits the original list in two and generates all the possible sublists where there are only two sublists. How can I generate all the possible sublists that can be created from original list where order is maintained?

like image 854
turtle Avatar asked Feb 10 '23 17:02

turtle


1 Answers

How about:

import itertools

def subsets(seq):
    for mask in itertools.product([False, True], repeat=len(seq)):
        yield [item for x, item in zip(mask, seq) if x]

def ordered_groups(seq):
    for indices in subsets(range(1, len(seq))):
        indices = [0] + indices + [len(seq)]
        yield [seq[a:b] for a,b in zip(indices, indices[1:])]

for group in ordered_groups([1,3,7,8,9]):
    print group

Result:

[[1, 3, 7, 8, 9]]
[[1, 3, 7, 8], [9]]
[[1, 3, 7], [8, 9]]
[[1, 3, 7], [8], [9]]
[[1, 3], [7, 8, 9]]
[[1, 3], [7, 8], [9]]
[[1, 3], [7], [8, 9]]
[[1, 3], [7], [8], [9]]
[[1], [3, 7, 8, 9]]
[[1], [3, 7, 8], [9]]
[[1], [3, 7], [8, 9]]
[[1], [3, 7], [8], [9]]
[[1], [3], [7, 8, 9]]
[[1], [3], [7, 8], [9]]
[[1], [3], [7], [8, 9]]
[[1], [3], [7], [8], [9]]
like image 69
Kevin Avatar answered Feb 12 '23 08:02

Kevin