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
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()
Comments
Leave a comment