在输入中,我们有包含任意行和列计数的矩阵,例如:
1 2 3
4 5 6
7 8 9在产出方面应:
1 4 7 8 9
0 2 5 6 0
0 0 3 0 0我试着写代码,但我有很多错误,我觉得我选择了错误的方式,我所有的研究都错了。如何解决这个问题?
我是一名学生,我的老师给了我这个任务,这是出乎意料的,因为我在码战训练,忘记学习矩阵和numpy,我有两个小时,有什么可以帮助我吗?
发布于 2020-11-20 08:28:01
该死!!我有点晚了,party.Try这个。a = (np.r_[t[0:rows-i,i],t[rows-1-i,i+1:]])是code.Which的核心,它获取矩阵的外部值,并在每个iteration.next中以0连接数组。
import numpy as np
t=np.array([[1, 2, 3],
[4 ,5 ,6],
[7, 8 ,9]])
result = []
rows,columns = t.shape
for i in range(rows):
a = np.r_[t[0:rows-i,i],t[rows-1-i,i+1:]]
pad = int(((rows+columns)-1-len(a))/2)
a = np.pad(a,(pad,pad), 'constant', constant_values=(0,0))
result.append(list(a))
print(result)输出
[[1, 4, 7, 8, 9], [0, 2, 5, 6, 0], [0, 0, 3, 0, 0]]输入
t=np.array([[1, 2, 3,4],
[4 ,5 ,6,10]])输出
[[1, 4, 5, 6, 10], [0, 2, 3, 4, 0]]发布于 2020-11-20 08:05:04
您需要在每次迭代中获得外部值。

比如,首先你需要得到粉红色箭头值,然后是红色,然后是其余的值。
首先,您需要创建从1到10的矩阵。
A = np.arange(1, 10).reshape(3, 3)然后,使用递归,您将获得外部值,您可以使用计数器(cnt)来实现这一点:
import numpy as np
def get_mat(mat, cnt, col):
if cnt == mat.shape[0]:
return col
for i in range(cnt):
col.append(0)
for i in range(0, len(mat) - cnt):
m = mat[i]
col.append(m[cnt])
for r in m[cnt+1:]:
col.append(r)
for i in range(cnt):
col.append(0)
return get_mat(mat, cnt+1, col)
A = np.arange(1, 10).reshape(3, 3)
cols = []
res = get_mat(A, 0, cols)
res = np.reshape(res, (3, 5))
print(res)结果:
[[1 4 7 8 9]
[0 2 5 6 0]
[0 0 3 0 0]]发布于 2020-11-20 07:55:10
完全代码
input_array=[[1,2,3],[4,5,6],[7,8,9]] #input array
row=len(input_array) #no of rows in array
col=len(input_array[0]) #no of columns in array
for i in range(0,col): #iterating for each head value
turn=row-i
for j in range(0,turn): #itearing and taking turn
if j==0:
for l in range(i): #for printing zeros in the beginning
print(0,end=" ")
if j<=row:
print(input_array[j][i],end=" ")
if j==turn-1: #taking turn
for k in range(i+1,row):
print(input_array[j][k],end=" ")
for l in range(i): #for printing zeros in the beginning
print(0,end=" ")
print("\n") #line break输出

为了你的方便,我评论了这段代码。如果您对代码有任何疑问,请随时询问。
https://stackoverflow.com/questions/64925098
复制相似问题