Python 用于生成';Z';1和0的关系?
你知道怎么解决这个问题吗?我是python编程新手:(谢谢 问题: 给定一个大于2的正整数'n',创建一个大小为(nxn)的NumPy数组,该数组将包含所有的0和1,使这些1形成类似于'Z'的形状 示例: 输入1:Python 用于生成';Z';1和0的关系?,python,arrays,numpy,Python,Arrays,Numpy,你知道怎么解决这个问题吗?我是python编程新手:(谢谢 问题: 给定一个大于2的正整数'n',创建一个大小为(nxn)的NumPy数组,该数组将包含所有的0和1,使这些1形成类似于'Z'的形状 示例: 输入1:3,输出1: [[1 1 1] [0 1 0] [1 1 1]] 输入2:5——输出2: [[1 1 1 1 1] [0 0 0 1 0] [0 0 1 0 0] [0 1 0 0 0] [1 1 1 1 1]] 试试这个代码 import numpy as n
3
,输出1:
[[1 1 1]
[0 1 0]
[1 1 1]]
输入2:5——输出2:
[[1 1 1 1 1]
[0 0 0 1 0]
[0 0 1 0 0]
[0 1 0 0 0]
[1 1 1 1 1]]
试试这个代码
import numpy as np
n = int(input("Enter size:"))
data = np.zeros([n,n], dtype=int) # fill grid of nxn with zeros.
data[0] = data[n-1] = np.ones(n, dtype=int) # set first and last row to 1s.
j = n-2
for i in range(1,n-1): # fills diagonally 1s.
data[i][j] = 1
j-=1
print(data)
让我们试试
numpy
风格:
def get_z(n):
out = np.eye(n, dtype=np.int)
out[[0,-1]] = 1
return out[::-1]
get_z(5)
让我们完全在努比做吧 因此,我们将问题分为三个主要部分:
- np.zeros:返回一个给定形状和类型的新数组,并用零填充
- np.ones:返回一个给定形状和类型的新数组,并用1填充
- np.concatenate:沿现有轴连接一系列数组
- np.fill_diagonal:填充任意维给定数组的主对角线
- np.fliplr:沿左/右方向翻转阵列
(我相信可能有更多更好的方法)到目前为止,您尝试了什么?本着对StackOverflow提出好问题的精神,如果您能帮我们一点忙,您会得到更好的结果。例如,数组的第一行和最后一行似乎非常简单。只有一个长度为1的N的列表。您能先做这部分吗?嗨!感谢您的反馈:)下次我会记住的!我创建了零矩阵,并将顶行和底行更改为1,但在如何转换对角线方面遇到了难题:(
array([[1, 1, 1, 1, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 0, 0],
[1, 1, 1, 1, 1]])
import numpy as np
# given input size
N = 5
# first initializing with first row as all ones
rows_of_ones_zeros = np.ones((1, N), int)
# Now, there will be N-2 rows of zeros , and finally one more row of ones.
for i in range(N-2):
rows_of_ones_zeros = np.concatenate((rows_of_ones_zeros, np.zeros((1, N), int)))
else:
rows_of_ones_zeros = np.concatenate((rows_of_ones_zeros, np.ones((1, N), int)))
# fill the main diagonal elements with 1
np.fill_diagonal(rows_of_ones_zeros, 1)
# now, flip it
rows_of_ones_zeros = np.fliplr(rows_of_ones_zeros)
import numpy as np
n=int(input())
a=np.zeros((n,n),dtype=int)
### since to form a "Z", the row + column index adds upto n-1
for row in range(n):
for col in range(n):
if row==0 or row ==n-1 or (row+col==n-1):
a[row][col]=1
print(a)