
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find diagonal sum of a matrix in Python
Suppose we have a square matrix; we have to find the sum of the matrix diagonals. So only include the sum of all of the elements on the primary diagonal and all the elements on the secondary diagonal and ignore the crossing element.
So, if the input is like
10 | 5 | 9 | 6 |
8 | 15 | 3 | 2 |
3 | 8 | 12 | 3 |
2 | 11 | 7 | 3 |
then the output will be The primary diagonal elements are [10,15,12,3] sum is 40, secondary diagonal [6,3,8,2] sum is 19, so total sum 59.
To solve this, we will follow these steps −
m := row count of matrix
if m is same as 1, then
return matrix[0, 0]
count := 0
for i in range 0 to m - 1, do
count := count + matrix[i, i]
count := count + matrix[i, (-1 - i)]
if m is odd, then
ind := quotient of m/2
count := count - matrix[ind, ind]
return count
Example (Python)
Let us see the following implementation to get better understanding −
def solve(matrix): m = len(matrix) if m == 1: return matrix[0][0] count = 0 for i in range(m): count += matrix[i][i] count += matrix[i][-1 - i] if m % 2 == 1: count -= matrix[m // 2][m // 2] return count matrix = [[10,5,9,6],[8,15,3,2],[3,8,12,3],[2,11,7,3],] print(solve(matrix))
Input
[[10,5,9,6],[8,15,3,2],[3,8,12,3],[2,11,7,3]]
Output
59
- Related Articles
- Python Program to calculate the sum of right diagonal the matrix
- Python Program to calculate the sum of left diagonal of the matrix
- Golang program to calculate the sum of left diagonal matrix
- How to find the sum of anti-diagonal elements in a matrix in R?
- Swift Program to calculate the sum of right diagonal of the matrix
- Swift Program to calculate the sum of left diagonal of the matrix
- Program to find sum each of the diagonal path elements in a binary tree in Python
- Program to convert given Matrix to a Diagonal Matrix in C++
- JavaScript Program to Generate a matrix having sum of secondary diagonal equal to a perfect square
- Program to print a matrix in Diagonal Pattern.
- Python Program to Remove First Diagonal Elements from a Square Matrix
- Program to check diagonal matrix and scalar matrix in C++
- Program to find the sum of elements that forms a Z shape on matrix in Python
- Find Multiplication of Diagonal Elements of a Matrix in Java
- Golang program to print right diagonal matrix
