子矩阵右对角线 - Python
Sub Matrices right diagonal - Python
程序必须接受大小为 RxC
的整数矩阵和一个整数 K
,因为 input.The 程序必须打印左下角到顶部的所有整数 right diagonal
在每个 KxK
子矩阵中没有给定矩阵的任何重叠
NOTE: The values of R and C ara always multiples of K
示例:
Input:
4 4
1 2 3 4
5 6 7 9
8 5 4 1
6 9 0 5
2
Output:
5 2
7 4
6 5
0 1
我的代码:
row , col = map(int,input().split())
mat = [list(map(int,input().split())) for i in range(row)]
k = int(input())
temp = k
# To store the right diagonal elements of all the sub matrices
right_diagonal_elements = []
for i in range(row):
te =temp
# Iterating through the matrix in such a way
#that it appends only the k th element ,
#then k-1, and so on til the first element
while te<=col:
# It appends the right diagonal element but in a different order
right_diagonal_elements.append(mat[i][te-1])
te+=k
if temp == 1:
temp = k
continue
temp -= 1
在这段代码中,我的代码获得了所有正确的对角线元素,但我一直在思考如何安排它以获得给定的输出
对于上面的示例,right_diagonal_elements 具有 [2, 4, 5, 7, 5, 1, 6, 0]
。我坚持如何在列表中排列这些元素以获得示例
中的输出
如果你想打印所有子矩阵的右对角线那么
R, C = map(int, input().split())
mat = [list(map(int, input().split())) for _ in range(R)]
K = int(input())
#iterating from k-1 to R by K
for i in range(K - 1, R, K):
# Iterating j from 0 to C by K
for j in range(0, C, K):
# Iterating through the sub matrix of size KxK
for p in range(K):
print(mat[i-p][j+p], end=' ')
print()
程序必须接受大小为 RxC
的整数矩阵和一个整数 K
,因为 input.The 程序必须打印左下角到顶部的所有整数 right diagonal
在每个 KxK
子矩阵中没有给定矩阵的任何重叠
NOTE: The values of R and C ara always multiples of K
示例:
Input:
4 4
1 2 3 4
5 6 7 9
8 5 4 1
6 9 0 5
2
Output:
5 2
7 4
6 5
0 1
我的代码:
row , col = map(int,input().split())
mat = [list(map(int,input().split())) for i in range(row)]
k = int(input())
temp = k
# To store the right diagonal elements of all the sub matrices
right_diagonal_elements = []
for i in range(row):
te =temp
# Iterating through the matrix in such a way
#that it appends only the k th element ,
#then k-1, and so on til the first element
while te<=col:
# It appends the right diagonal element but in a different order
right_diagonal_elements.append(mat[i][te-1])
te+=k
if temp == 1:
temp = k
continue
temp -= 1
在这段代码中,我的代码获得了所有正确的对角线元素,但我一直在思考如何安排它以获得给定的输出
对于上面的示例,right_diagonal_elements 具有 [2, 4, 5, 7, 5, 1, 6, 0]
。我坚持如何在列表中排列这些元素以获得示例
如果你想打印所有子矩阵的右对角线那么
R, C = map(int, input().split())
mat = [list(map(int, input().split())) for _ in range(R)]
K = int(input())
#iterating from k-1 to R by K
for i in range(K - 1, R, K):
# Iterating j from 0 to C by K
for j in range(0, C, K):
# Iterating through the sub matrix of size KxK
for p in range(K):
print(mat[i-p][j+p], end=' ')
print()