尺寸为x的1的二维阵列菱形

2024-04-27 03:48:42 发布

您现在位置:Python中文网/ 问答频道 /正文

嘿,我正在尝试制作一个由1和0组成的二维数组,其中1形成菱形。钻石的尺寸应为x:

尺寸x=3的菱形形状如下所示:

[[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]]

尺寸x=1的菱形形状如下所示:

[[1]]

有人知道如何实现这一点吗?我认为numpy.eyeconcatenate可能有用。然而,我找不到解决办法


Tags: numpy尺寸数组形状eye钻石菱形concatenate
3条回答

我将以以下方式利用numpy.diagflatnumpy.flip的结合:

import numpy as np
arr = np.diagflat([1,1,1],2)  # now we have 1s in upper-right part
arr = np.maximum(arr,np.flip(arr,1))  # now we have 1s in upper part
arr = np.maximum(arr,np.flip(arr,0))  # now we have 1s everywhere
print(arr)

输出:

[[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]]

这里有一个np.eye的解决方案

import numpy as np

def diamond(n):
    a, b = np.eye(n, dtype=int), np.eye(n, dtype=int)[:,::-1]

    c, d = np.hstack((b,a[:,1:])), np.hstack((a,b[:,1:]))

    return np.vstack((c, d[1:,:]))

输出:

>>> print(diamond(3))

[[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]]

使用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)

相关问题 更多 >