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.
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 without square brackets :
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
def printMatrix(matrix, i, j):
for x in range(i):
for row in range(j):
print(matrix[x][row], end=" ")
print()
def makeDiagonalNotZero(matrix, row, col):
for x in range(row):
for y in range(col):
# Left and right diagonal condition
if (x == y or (x + y + 1) == n):
(matrix[x][y])
else:
matrix[x][y] = 0
# Displaying the matrix
printMatrix(matrix, row, col)
#Testing code
if __name__ == "__main__":
n = 5
m = 5
mat = [[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]]
makeDiagonalNotZero(mat, n, m)
Comments
Leave a comment