Answer to Question #218764 in Python for sudheer

Question #218764

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


1
Expert's answer
2021-07-19T04:19:09-0400
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)

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