def nzeros(a, n):
# Define kernel for 1D convolution
k = np.ones(n,dtype=int)
# Get sliding summations for zero matches with that kernel
s = np.convolve(a==0,k)
# Look for summations that are equal to n value, which will occur for
# n consecutive 0s. Remember that we are using a "full" version of
# convolution, so there's one-off offsetting because of the way kernel
# slides across input data. Also, we need to create 1s at places where
# n consective 0s end, so we would need to slice out ending elements.
# Thus, we would end up with the following after int dtype conversion
return (s==n).astype(int)[:-n+1]
def nzeros(a, n):
#Create a numpy array of zeros of length equal to n
b = np.zeros(n)
#Create a numpy array of zeros of same length as array a
c = np.zeros(len(a), dtype=int)
for i in range(0,len(a) - n):
if (b == a[i : i+n]).all(): #Check if array b is equal to slice in a
c[i+n-1] = 1
return c
方法1
我们可以使用^{} convolution -
样本运行-
^{pr2}$方法2
另一种解决这个问题的方法可以看作是}的掩码。因此,我们可以使用^{} ^{} ,它也允许我们用它的
1D
卷积方法的一种变体,它是使用erosion
,因为如果你看一下输出,我们可以简单地从开始到n-1
处侵蚀{origin
参数指定内核中心的部分,因此我们将避免任何切片。实现应该是这样的-使用for循环:
样本输出:
^{pr2}$相关问题 更多 >
编程相关推荐