Python: get the minimum length of space that captures all the non zero values of an array with looping allowed

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x