# divide an array using a changing length sequence of boolean var as index

i have an array of boolean variables. The array has a sort of structure, it's formed of many sequences of zeros and ones, sequences of different length. such as:

[1111111100001111111111000000000000001111111000000111111111111111110000]

"commas omitted between values"

i need to separate it in this way

[111111110000],[111111111100000000000000],[1111111000000],[111111111111111110000]

Someone knows a good way or just a way to do this ?

Algorithm could be language free, but in case you know how to do it in python you are welcome.

After some struggling i found a way to divide the array, but only if it begins with ONES. I realy can't figure out how to make it work with array beginning with 1 or 0.

import numpy as np

x = np.asarray([1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,0,0,0,0,0,0,1,1,1,1,0,0,0])

c = 1

for i in range(len(x)):
if x[i] == 1:
if c == 0:
print "\n\tDIVIDE\n"
c = 1
print "one"

else:
if c == 1:
c = 0
print "zero"

• The answer provided still gives you the information you need, but your question doesn't quite state what you intend to do when the array leads with 0. Do you then want all the result arrays to lead with 0, or do you want the first array to only have 0? May 15 '15 at 5:19
• i read the first element of the array and i set a variables, say START to -1 if it starts with 1 or START=1 if array starts with 0. Then i only need to check condition np.diff(x) == START.
– arj
May 15 '15 at 8:46

Get the indices, where you want to split:

>>> np.diff(x)
array([ 0,  0, -1,  0,  0,  0,  0,  0,  0,  0,  1,  0,  0,  0,  0,  0,  0,
0,  0,  0,  0,  0, -1,  0,  1,  0,  0, -1,  0,  0,  0,  0,  0,  1,
0,  0,  0, -1,  0,  0])


Every 1 denotes the change from 0 to 1.

Apply it (shifted by one index of course):

>>> np.split(x, np.nonzero(np.diff(x) == 1)[0]+1)
[array([1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]), array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]), array([1, 1, 1, 0, 0, 0, 0, 0, 0]), array([1, 1, 1, 1, 0, 0, 0])]

• Great! You made clear the difference between a real programmer, you, and a human scripter , me. Thanks!
– arj
May 10 '15 at 14:19
• I would like to upvote, but my reputation is sitll 6. I can't sorry.
– arj
May 10 '15 at 21:09