Get diagonal without using numpy?

Viewed 31005

I'm trying to get the diagonal from a matrix in Python without using numpy (I really can't use it). Does someone here knows how to do it?

Example of what I want to get:

get_diagonal ([[1,2,3,4],[5,6,7,8],[9,10,11,12]], 1, 1, 1)
Result: [1, 6, 11]

Or like:

get_diagonal ([[1,2,3,4],[5,6,7,8],[9,10,11,12]], 1, 2, 1)
Result: [2, 7, 12]

Until know I've tried a lot of stuff but doesn't work.

def obter_diagonal(matrix, line, column, direc):
    d = []
    if direc == 1:
        for i in matrix:
            for j in i:
                if all(i == line, j == column):
                    d.extend(matrix[i][j])
    else:
        for i in matrix:
            for j in i:
                d.extend[len(matrix)-1-i][j]
    return d

If direc==1 I need to get the diagonal that goes from left-> right, top-> bottom.
If direc==-1 need to get the diag that goes from right-> left, top->bottom.

6 Answers
lis = []
lis2 = []
count = len(a)-1
count2 = 0
for i in range(len(a)):
   lis.append(a[count2][count])
   count-=1
   count2+=1
for i in range(len(a)):
   lis2.append(a[i][i])

print(lis,lis2)

This print both the right and left diagonal

Related