Answer to Question #168607 in Python for srikanth

Question #168607
Given a MxN matrix,write a program to print all Anti-Diagonals elements of matrix

Input

The first line of input will contain a M, N values separated by space.
The second line will contain matrix A of dimensions MxN.

Output

The output should contain anti-diagonal elements separated by a line.
Explanation

For example, if M = 4, N = 4
Matrix A:




4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
So the output should be

1
2 5
3 6 9
4 7 10 13
8 11 14
12 15
16
Sample Input 1
2 3
1 5 5
2 7 8
Sample Output 1
1
5 2
5 7
8

Sample Input 2
3 4
1 2 3 4
5 6 7 8
9 10 11 12
Sample Output 2
1
2 5
3 6 9
4 7 10
8 11
12
1
Expert's answer
2021-03-05T16:22:34-0500
m, n = input('Enter the values of M and N separated by a space: ').split()
m = int(m)
n = int(n)
matrix_str = input('Enter all matrix values separated by a space: ').split()

matrix = [matrix_str[n*i:n*(i+1)] for i in range(m)]

for i in range(n):
    for j in range(i+1):
        try:
            print(matrix[j][i-j],end=' ')
        except:
            break
    print('')

for i in range(1,m):
    for j in range(i+1):
        try:
            print(matrix[i+j][-1-j],end=' ')
        except:
            break
    print('')  

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

priyanka
07.04.21, 08:57

its not giving exact output? for ex: Sample Input 1 2 3 1 5 5 2 7 8 Sample Output 1 1 5 5 it showing only this.its not the desired output please rectify it?

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS