Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split an array in all possible combinations (not regular splitting)

Suppose I have an array,

>>> import numpy as np
>>> array  = np.linspace(1,4,4, dtype=np.int)
>>> array
array([1, 2, 3, 4])

I want a function that will split this array in all possible parts, such that,

No split :

([1,2,3,4])

Split in 2 parts :

([1], [2,3,4])
([1,2], [3,4])
([1,2,3] ,[4])

Split in 3 parts :

([1], [2], [3,4])
([1,2]), [3], [4])
([1], [2,3], [4])

Split in len(array) parts :

([1],[2],[3],[4])

I know there is np.split(array, r), but it will not give all possible splits. e.g. np.split(array, 2) will give,

[array([0, 1]), array([2, 3])]

As you can see this is not what I need. How to achieve my need?

like image 339
ddas Avatar asked Sep 12 '25 03:09

ddas


1 Answers

You could use itertools.combinations to generate the indices where to split inside a loop over the number of splits:

>>> from itertools import combinations
>>> [np.split(array, idx) 
...  for n_splits in range(5) 
...  for idx in combinations(range(1, len(array)), n_splits)]
[[array([1, 2, 3, 4])],
 [array([1]), array([2, 3, 4])],
 [array([1, 2]), array([3, 4])],
 [array([1, 2, 3]), array([4])],
 [array([1]), array([2]), array([3, 4])],
 [array([1]), array([2, 3]), array([4])],
 [array([1, 2]), array([3]), array([4])],
 [array([1]), array([2]), array([3]), array([4])]]
like image 183
MSeifert Avatar answered Sep 14 '25 17:09

MSeifert