I need to write a function that will return the sum of numbers that form a diagonal in any given matrix.
Being a Python newbie I've got a problem. This is my code:
def diagonal(matrix):
return sum([matrix[i][i] for i in range(len(matrix))])
I've been trying for some time now but don't see what is wrong because it always gives me back report about error saying "list index out of range".
I am not allowed to import numpy
.
Any form of help, hint, advice would be appreciated.
If you are sure that your matrix is rectangular (
len(matrix[i])
is the same for all lists inmatrix
), then you can sum your list only as long as your smaller dimension goes:len(matrix)
is the first dimension of your matrix, andlen(matrix[0])
is the dimension of the first row vector, which is the second dimension for rectangular matrices.