Given an MxN matrix, write a program to print all Anti-Diagonals elements of the matrix
Input:
The first line of input will contain 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.
Sample Input 1:
2 3
1 5 5
2 7 8
Output:
1
5 2
5 7
8
Sample Input 2:
3 4
1 2 3 4
5 6 7 8
9 10 11 12
Output:
1
2 5
3 6 9
4 7 10
8 11
12
def antidiag(matrix):
"""Prints anti-diagonals of matrix. One per line.
>>> antidiag([
... [1, 5, 5],
... [2, 7, 8]
... ])
1
5 2
5 7
8
>>> antidiag([
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12]
... ])
1
2 5
3 6 9
4 7 10
8 11
12
>>> antidiag([
... [1, 2],
... [3, 4],
... [5, 6],
... [7, 8]
... ])
1
2 3
4 5
6 7
8
>>> antidiag([
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... [10, 11, 12]
... ])
1
2 4
3 5 7
6 8 10
9 11
12
"""
M = len(matrix)
N = len(matrix[0])
result = [[] for _ in range(M+N -1)]
for i in range(M):
for j in range(N):
result[i+j].append(matrix[i][j])
for d in result:
print(*d)
# Program
M, N = list(int(x) for x in input('M N: ').split())
A = []
for i in range(M):
A.append([int(x) for x in input('A[%d]: ' % (i+1)).split()])
antidiag(A)
if __name__ == '__main__':
import doctest
doctest.testmod()
Comments
Leave a comment