Answer to Question #217695 in Python for sudheer

Question #217695

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.

input: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

output should be like this: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-07-16T01:04:15-0400
n, m = input('n * m ').split()
n, m = int(n), int(m)
M = []
for i in range(n):
    tmp = list(int(el) for el in input().split())
    if len(tmp) != m:
        raise ValueError
    M.append(tmp)
for i in range(n):
    for j in range(m):
        if i == j or i == m-j-1:
            continue
        else:
            M[i][j] = 0
for row in M:
    print(row, sep=' ')

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