Answer to Question #183891 in Python for phani

Question #183891
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.
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

Sample Input 1
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
Sample Output 1
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

Sample Input 2
10 10
73 18 100 29 91 98 5 45 16 18
11 25 81 76 95 71 22 80 81 11
28 82 87 24 65 43 21 4 47 98
99 30 62 87 30 60 80 33 71 38
61 15 64 4 86 39 49 24 95 100
78 45 30 87 28 9 75 50 3 75
Sample Output 2
73 0 0 0 0 0 0 0 0 18
0 25 0 0 0 0 0 0 81 0
0 0 87 0 0 0 0 4 0 0
0 0 0 87 0 0 80 0 0 0
0 0 0 0 86 39 0 0 0 0
0 0 0 0 28 9 0 0 0 0
1
Expert's answer
2021-04-21T18:23:01-0400
def print_1(mat, n, m):
    for i in range(n):
        for j in range(m):
            print(mat[i][j], end=" ")

        print()


def makediagonalnotzero(mat, n, m):
    for i in range(n):
        for j in range(m):

            # right and left diagonal condition
            if (i == j or (i + j + 1) == n):
                (mat[i][j])
            else:
                mat[i][j] = 0

    # print resultant matrix
    print_1(mat, n, m)


# Driver code
if __name__ == "__main__":
    n = 3
    m = 3
    mat = [[2, 1, 7],
           [3, 7, 2],
           [5, 4, 9]]

    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