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?
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With