Answer to Question #180147 in Python for vijay

Question #180147

Given a MxN matrix, write a program to replace all elements that do not belong to principal-diagonal & anti-diagonal with Zeros.

Principal-diagonal elements are the set of elements of a matrix that lie on the line joining the top left corner to the bottom right corner.

Anti-diagonal elements are the set of elements of a matrix that lie on the line joining the bottom left corner to the top right corner.Input


The first line of input will contain two space-separated integers, denoting MxN matrix.

The next M lines will contain N space-separated integers.Output


The output should be MxN matrix by replacing elements that do not belong to principal-diagonal and anti-diagonal with Zeros. Print each row as a space separated integers in a single line.

Sample Input 1

5 5

4 3 7 6 4

4 4 7 7 6

9 5 8 5 9

3 6 6 2 4

3 7 4 4 3

Sample Output 1

4 0 0 0 4

0 4 0 7 0

0 0 8 0 0

0 6 0 2 0

3 0 0 0 3


1
Expert's answer
2021-04-11T01:14:37-0400
def print_1(mat, n, m):
    for i in range(n):
        for j in range(m):
            print(mat[i][j], end=" ")

        print()


def makediagonalnotzero(mat, n, m):
    for i in range(n):
        for j in range(m):

            # right and left diagonal condition
            if (i == j or (i + j + 1) == n):
                (mat[i][j])
            else:
                mat[i][j] = 0

    # print resultant matrix
    print_1(mat, n, m)


# Driver code
if __name__ == "__main__":
    n = 3
    m = 3
    mat = [[2, 1, 7],
           [3, 7, 2],
           [5, 4, 9]]

    makediagonalnotzero(mat, n, m)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS