Sum of the Diagonals

Upasana | June 21, 2019 | 1 min read | 5 views

Given a square matrix of size N by N, calculate the sums of its diagonals. There are two diagonals in each array.

def get_sum_of_diagonals(mat):
    sd1 = 0
    sd2 = 0
    for i in range(0, len(mat)):
        for j in range(0, len(mat)):
            if (i == j):
                sd1 += mat[i][j]
            if ((i + j) == (len(mat)-1)):
                sd2 += mat[i][j]
    return sd1+sd2

mat = [[1,2,9],[4,5,6],[18,8,12]]

Top articles in this category:
  1. Python coding challenges for interviews
  2. Count the number of open lockers in school
  3. Pass the ball game: NxN matrix in python
  4. Google Data Scientist interview questions with answers
  5. Top 100 interview questions on Data Science & Machine Learning
  6. Flask Interview Questions
  7. Sequence of Differences in Python

Recommended books for interview preparation:

Find more on this topic: