2

Trying to get all the diagonal elements of a NXN matrix without using numpy,

This is different from Get diagonal without using numpy in Python

Please don't mark as duplicate.

Here is my snippet using two iteration, it will print all the diagonal element from (0,0) to (n,n). Could some one help me in improving my iteration process or any recursive way to do it.

#!/usr/bin/python 

matrix = [[1,2,3,4], 
          [2,3,4,5], 
          [3,4,5,6], 
          [4,5,6,7]] 

def get_matrix_diagonal(m): 
    col = len(m) 
    result = list() 
    row = 0 
    for c in range(col): 
        position = list() 
        position.append([row,c]) 
        if c > 0: 
            i = c 
            while i > 0: 
                x = i - 1 
                y = c - i + 1 
                position.append([y,x]) 
                i -= 1 
        result.append(position) 
    row = row + 1 
    cc = c 
    for i in range(row,col): 
        position = list() 
        y = i 
        x = c 
        position.append([y,x]) 
        j = x - y 
        while j > 0: 
            y = c - j + 1 
            x = cc - y + 1 
            position.append([y,x]) 
            j -= 1 
        cc += 1
        result.append(position)
    return result

for ls in get_matrix_diagonal(matrix):
    for co in ls:
        x,y = co[0],co[1],
        print matrix[x][y],
    print

Output:

1
2 2
3 3 3
4 4 4 4
5 5 5
6 6
7
Community
  • 1
  • 1
James Sapam
  • 16,036
  • 12
  • 50
  • 73

2 Answers2

6
>>> matrix = [[1,2,3,4], 
...           [2,3,4,5], 
...           [3,4,5,6], 
...           [4,5,6,7]] 
>>> N = 4
>>> [[matrix[y-x][x] for x in range(N) if 0<=y-x<N] for y in range(2*N-1)]
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5], [6, 6], [7]]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
2

Here an recursive approach supposing your matrix is square:

def diagonals(m):
    if len(m) == 1: return m
    d = [[]] + diagonals([r[1:] for r in m[:-1]]) + [[]]
    r = [r[0] for r in m] + m[-1][1:]
    return [[r] + d for r, d in zip(r,d)]
Hyperboreus
  • 31,997
  • 9
  • 47
  • 87