Answer to Question #186199 in Python for Hari nadh babu

Question #186199

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

The first line of input will contain a M, N values separated by space.

The second line will contain matrix A of dimensions MxN.

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

For example, if M = 4, N = 4

Matrix A:


Input :

2 3

1 5 5

2 7 8

Output must be

1

5 2

5 7

8


the output must be like this only without any extra messages


1
Expert's answer
2021-04-27T07:16:15-0400
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

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS