I am trying to find out the sum of the diagonal elements in a matrix. Here, n is the size of the square matrix and a is the matrix. Can someone explain this to me what is happen
Since you know the positions of the diagonal elements for row i, you can write it quite densely like:
i
d = sum(row[i] + row[-1-i] for i, row in a)
And, for odd sized matrices, you shouldn't add the center element twice:
if len(a)%2: centre = len(a)//2 d -= a[centre][centre]