Answer to Question #166820 in Python for prathyusha

Question #166820

Anti-Diagonals

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-02-26T05:37:00-0500
def antidiagonals(M, N, matrix):
    """Prints antidiagonals one per line of MxN matrix represented
        by 1-dimantional array

    >>> antidiagonals(2, 3, [1, 5, 5, 2, 7, 8])
    1
    5 2
    5 7
    8
    >>> antidiagonals(3, 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
    1
    2 5
    3 6 9
    4 7 10
    8 11
    12
    """
    antidiagonals = [[] for _ in range(M+N-1)]
    for i in range(M*N):
        adindex = (i // N) + (i % N)
        antidiagonals[adindex].append(matrix[i])
    for d in antidiagonals:
        print(*d)

# Driver code
M, N = list(map(int, input('M N: ').split()))
A = []
for i in range(1, M+1):
    A += map(int, input('A[%d]: ' % i).split())

antidiagonals(M, N, A)

if __name__ == '__main__':
  import doctest
  doctest.testmod(verbose=True)

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

Assignment Expert
05.05.21, 12:30

Dear coolboy, Questions in this section are answered for free. We can't fulfill them all and there is no guarantee of answering certain question but we are doing our best. And if answer is published it means it was attentively checked by experts. You can try it yourself by publishing your question. Although if you have serious assignment that requires large amount of work and hence cannot be done for free you can submit it as assignment and our experts will surely assist you.

coolboy
05.05.21, 06:16

M N: A[1]: A[2]: 1 5 2 5 7 8 i want to remove this part from output M N: A[1]: A[2]: how to do that

Assignment Expert
30.03.21, 19:11

Dear SriHari Srinivas, please use panel for submitting new questions

SriHari Srinivas
30.03.21, 18:01

Can you explain the logic behind the program, Please

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS