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.signessentially reduces each value in the array to it’s sign, so negative numbers become-1, positive numbers become1, and0stays0.np.argmaxreturns the 0-based index of the first occurence of the largest value in the array, which will be1due tonp.sign, so it will be the index of the first1, which works nicely for this case.np.cumsumperforms 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, sonp.argmaxagain 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