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?
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])]]
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