Answer to Question #189422 in Python for suresh

Question #189422

Replace Elements with Zeros

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.Explanation


For example if the M and N are 5 and 5. Read the elements of 5 rows in next 5 lines. If the given elements are


1
Expert's answer
2021-05-05T07:29:46-0400
inpt = input().split()
M = int(inpt[0])
N = int(inpt[1])

mat = []
for _ in range(M):
    inpt = input().split()
    mat.append([int(s) for s in inpt])

for i in range(M):
    for j in range(N):
        if i != j and i+j+1 != N:
            mat[i][j] = 0

for i in range(M):
    for j in range(N):
        print(mat[i][j], end=' ')
    print()

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