首页 > 解决方案 > using 1's in the arrays to make a shape like '+' using numpy in python

问题描述

Numpy Three Four Five Dimensional Array in Python

Input 1: 3

Output 1:

[[0 1 0]

 [1 1 1]

 [0 1 0]]

Input 2:5

Output 1:

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

Notice that the 1s in the arrays make a shape like +.

My logic is shown below

a=np.zeros((n,n),dtype='int')
a[-3,:] = 1
a[:,-3] = 1 print(a)

This logic is only working for five dimensional array but not for three dimensional array.

can someone assist me to get the expected output for both three and five dimensional array using np.zeros & integer division //

标签: pythonarraysnumpy

解决方案


如您所见,n//2 = 3n=5. 因此,这就是您的问题的解决方案,如下所示:

import numpy as np

def create_plus_matrix(n):
    a = np.zeros((n,n),dtype='int')
    a[-n//2,:] = 1
    a[:,-n//2] = 1
    return a

所以,让我们尝试一下:

>>> create_plus_matrix(3)
[[0 1 0]
 [1 1 1]
 [0 1 0]]

>> create_plus_matrix(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]]

推荐阅读