python-3.xlistmatrixsubmatrix

Sub Matrices right diagonal - Python


The program must accept an integer matrix of size RxC and an integer K as the input.The program must print all the integers in the bottom left to top right diagonal in each KxK sub matrix without any overlapping of the given matrix

NOTE: The values of R and C ara always multiples of K

Example :

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

My Code :

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

In this my code gets all the right diagonal elements, but I am stuck on how to arrange it in such a way that it obtains the given output
The right_diagonal_elements has [2, 4, 5, 7, 5, 1, 6, 0] for the example above. I am stuck on how to arrange this elements in the list in order to get the output in example


Solution

  • If you want to print all the sub matrices right diagonal then

    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()