Home > Software design >  Python: get the minimum length of space that captures all the non zero values of an array with loopi
Python: get the minimum length of space that captures all the non zero values of an array with loopi

Time:05-04

Examples:

1)

 v                 v
[1,0,0,1,1,1,1,0,1,1,0,0,0]
 ^                 ^

would return a result of 10 as this is the minimum length of space between the first instance of a nonzero value and the last (bolded). If we instead considered the following:

                 v v
[1,0,0,1,1,1,1,0,1,1,0,0,0] 
                 ^ ^

and looped to capture all the nonzero values, the length of space would be 13 so 10 is our answer.

2)

     v             v
[0,0,1,0,0,0,0,0,0,1,1]
     ^             ^

would return a result of 5 since looping is allowed. If we instead considered the following:

     v               v
[0,0,1,0,0,0,0,0,0,1,1] 
     ^               ^

and did not loop, the length of space would be 9 so 5 is our answer.

CodePudding user response:

You can use np.sign np.argmax to the find the index of the first non-zero value, and np.cumsum np.argmax to find the index of the last non-zero value. Then subtract those:

>>> a = [1,0,0,1,1,1,1,0,1,1,0,0,0]
>>> np.cumsum(a).argmax() - np.sign(a).argmax()   1
9
  • np.sign essentially reduces each value in the array to it's sign, so negative numbers become -1, positive numbers become 1, and 0 stays 0.
  • np.argmax returns the 0-based index of the first occurence of the largest value in the array, which will be 1 due to np.sign, so it will be the index of the first 1, which works nicely for this case.
  • np.cumsum performs a cumulative sum accross all the items of the array. Because of this, the first occurence of the largest value in the array will be the last non-zero value, so np.argmax again is perfect.
  • Related