-1

I have an Array of zeros and ones which looks like this:

mat = [0,0,0,1,1,0]

I need to write down a new array of positions where a zero/one starts and ends:

mat_help= [[0,3], [4,5], [6,6]] 

I thought I could accomplish this Task by simply loop. But then I got stucked: how can I mark the beginning of each zero?

In principle, I've ended up with this Code which Looks ugly and where I still should add a nestedness to the final list:

mat=[0, 0, 0, 1, 1, 0, 0]
matrix_length = len(mat)
mat_help=[0]
for i in range(len(mat)-1):
    if mat[i]==mat[i+1]:
        continue
    elif mat[i]!=mat[i+1]:
        mat_help.append(i)
        mat_help.append(i+1)
mat_help.append(matrix_length-1)

Maybe, there is a fast pythonic way of doing such things than just using several Loops...?

3
  • 2
    Please share the code you wrote. Also the array has only 6 elements whereas the positions in new_arr are 7 (from 0 to 6). Not sure if you know the problem statement very well Commented Jul 22, 2019 at 8:53
  • new_arr contains 6 as an index and yet it will raise IndexError given the length of the list is 6. Commented Jul 22, 2019 at 8:56
  • 4
    The expected output is inconsistent with the input. It should either be [0, 3], [3, 5], [5, 6] if the upper ends of the ranges are exclusive, or [0, 2], [3, 4], [5, 5] if they are inclusive, or [1, 3], [4, 5], [6, 6] if you start counting the indexes from 1, not 0 as is conventional. Please think more about what you want exactly, then the solution will probably follow naturally. Commented Jul 22, 2019 at 8:56

1 Answer 1

2

I'm not sure I understand what you're searching for, but you could try this :

def sep_groups(arr):
   if not arr:
      return []
   res = []
   start = 0
   type = arr[0]
   index = 0
   for current, next in zip(arr[:-1], arr[1:]):
      if next != type:
         res.append([start, index])
         start = index + 1
         type = 1 - type
      index += 1
   res.append([start, len(arr)-1])
   return res

I hope that will help you !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.