如何使用numpy数组以加号形式使用1打印图案

how to print a pattern using 1's in the form of plus sign using numpy array

如何使用 numpy 数组打印零内含 1 的加号模式!!我需要满足下面代码中尝试的所有 cases.I!!

代码:

n = int(input())
import numpy as np
x = np.zeros((n,n), dtype=int)
x[3:4] = 0
x[2:-1,2:3] = x[1:-1,2:3] = x[2:3] = x[0:-1,2:3] = x[4:,2:3]= 1
for i in range(n):
    for j in range(n):
        print(x[i][j] , end = " ")
    print()

输出:

[[0 0 1 0 0]
 [0 0 1 0 0]
 [1 1 1 1 1]
 [0 0 1 0 0]
 [0 0 1 0 0]]

您可以使用中间元素为 1(或 True)的数组进行广播:

n = int(input("size: "))
import numpy as np

r = np.arange(n)==n//2
r = r*1 | r[:,None]
print(r)

输出:

size: 5
[[0 0 1 0 0]
 [0 0 1 0 0]
 [1 1 1 1 1]
 [0 0 1 0 0]
 [0 0 1 0 0]]

解释:

r = np.arange(n)==n//2

生成一个 True/False 的数组,其中中间点(索引 n//2)为真,所有其他条目为假:

[False, False, True, False, False]

如果您使用 r[,:None] 将此 1x5 数组转换为 5x1 的形状,您将得到

[[False],
 [False],
 [ True],
 [False],
 [False]]

将这些 True/False 值乘以 1 将它们转换为数字,二进制或运算符 | 将在每一行广播到每一列时将它们保留在中间行和中间列中:

(OR)  0 0 1 0 0
    -----------
 0  | 0 0 1 0 0
 0  | 0 0 1 0 0
 1  | 1 1 1 1 1
 0  | 0 0 1 0 0
 0  | 0 0 1 0 0

请注意,有多种方法可以实现这一点。

这是另一个例子:

np.max(np.indices((n,n))==n//2,axis=0)*1

这是另一种解决方案,其中您有一个零数组,只需将中间的行和列设置为 1:

n = int(input())
a = np.zeros((n,n)).astype(int)
a[n//2,:]=a[:,n//2]=1
print(a)

[[0 0 1 0 0]
 [0 0 1 0 0]
 [1 1 1 1 1]
 [0 0 1 0 0]
 [0 0 1 0 0]]

假设是: 输入: 给定一个大于 2 的正奇数 'n'。

代码如下:

#读取输入
n = int(input())
#导入NumPy包
import numpy as np 
#创建一个全为零的 (n x n) 数组
arr = np.zeros((n, n), dtype = int)
#让中间行和中间列全为1
arr[n//2, :] = 1

arr[: , n//2] = 1
#打印arr的最终值
print(arr)
#完整代码如下:
n = int(input())
import numpy as np 
arr = np.zeros((n, n), dtype = int)
arr[n//2, :] = 1
arr[: , n//2] = 1
print(arr)

n=3 的示例输出:

[[0 1 0]
 [1 1 1]
 [0 1 0]]

n=5 的示例输出:

[[0 0 1 0 0]
 [0 0 1 0 0]
 [1 1 1 1 1]
 [0 0 1 0 0]
 [0 0 1 0 0]]

n=7 的示例输出:

[[0 0 0 1 0 0 0]
 [0 0 0 1 0 0 0]
 [0 0 0 1 0 0 0]
 [1 1 1 1 1 1 1]
 [0 0 0 1 0 0 0]
 [0 0 0 1 0 0 0]
 [0 0 0 1 0 0 0]]