Sum of diagonal elements in a matrix

后端 未结 11 1936
轻奢々
轻奢々 2021-02-12 11:42

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

11条回答
  •  说谎
    说谎 (楼主)
    2021-02-12 12:21

    I don't understand why no one posted any good solution. Here is as descent solution:

    length = len(arr)
    r1 = 0
    r2 = 0
    for i in range(length):
        r1 += arr[i][length - i - 1]
        r2 += arr[i][i]
    print(r1 + r2)
    # If you want sum of there absolute values
    print(abs(r1) + abs(r2))
    

    Here arr is a 2d list.

提交回复
热议问题