Sum of diagonal elements in a matrix

后端 未结 11 2470
有刺的猬
有刺的猬 2021-02-12 11:35

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:18

    Try this for summing your second diagonal:

    sum(a[i][n-i-1] for i in range(n))
    

    The inner loop accesses these entries:

    >>> n = 3
    >>> [(i, n-i-1) for i in range(n)]
    [(0, 2), (1, 1), (2, 0)]
    

    And the summed value of this diagonal for your sample matrix is:

    >>> n = 3
    >>> sum(a[i][n-i-1] for i in range(n))
    19
    

    The mistake in your code is to use the same expression for both dimensions:

    a[n-i-1][n-i-1]
    

    which will process the first diagonal again in reverse order [(2, 2), (1, 1), (0, 0)] giving you the same sum twice.

提交回复
热议问题