Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to compute the total of the diagonal values from a matrix. In my code, the n is the size of the square matrix and a is the matrix. Kindly explain the below code:

n = 3

a = [[11,2,4],[4,5,6],[10,8,-12]]

sum_first_diagonal = sum(a[i][i] for i in range(n))

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

print(str(sum_first_diagonal)+" "+str(sum_first_diagonal))

1 Answer

0 votes
by (108k points)
edited by

You can try the below code for calculating the diagonal of the elements:

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

The inner loop will access the below entries:

>>> n = 3

>>> [(i, n-i-1) for i in range(n)]

[(0, 2), (1, 1), (2, 0)]

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

>>> n = 3

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

19

In your code, the main error was that you have used the same syntax 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.

If you are a novice and want to understand more about Python basics then do refer to the Python certification program.

Related questions

0 votes
1 answer
asked Apr 2, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Feb 15, 2021 in SQL by RohitSingh (2.6k points)

Browse Categories

...