我的条目使用np.pad(... mode = 'reflect'):
def diamond(n):
return np.pad(np.eye(n), ((n-1, 0), (0, n-1)), mode = 'reflect')
diamond(3)
Out:
array([[0., 0., 1., 0., 0.],
[0., 1., 0., 1., 0.],
[1., 0., 0., 0., 1.],
[0., 1., 0., 1., 0.],
[0., 0., 1., 0., 0.]])
diamond(1)
Out: array([[1.]])
diamond(5)
Out:
array([[0., 0., 0., 0., 1., 0., 0., 0., 0.],
[0., 0., 0., 1., 0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 1., 0., 0.],
[0., 1., 0., 0., 0., 0., 0., 1., 0.],
[1., 0., 0., 0., 0., 0., 0., 0., 1.],
[0., 1., 0., 0., 0., 0., 0., 1., 0.],
[0., 0., 1., 0., 0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0., 1., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 0., 0., 0.]])
在我的时间里,这比@Daweo 的答案快 40%,而且代码也更简单
def diamond_Daweo(n):
arr = np.diagflat(np.ones(n), n-1) # now we have 1s in upper-right part
arr = np.maximum(arr,np.flip(arr,1)) # now we have 1s in upper part
return np.maximum(arr,np.flip(arr,0)) # now we have 1s everywhere
%timeit diamond_Daweo(100)
120 µs ± 1.9 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit diamond(100)
75.8 µs ± 2.86 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)