
- 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 the sum of elements that forms a Z shape on matrix in Python
Suppose we have one n x n matrix M, we have to find the sum of all elements that form a Z shape in the matrix.
So, if the input is like
4 | 3 | 2 |
9 | 1 | 8 |
2 | 5 | 6 |
then the output will be 23, as elements are [4+3+2+1+2+5+6] = 23.
To solve this, we will follow these steps −
- n := row count of matrix
- if n <= 2, then
- return sum of all elements in matrix
- first_row := sum of first row
- last_row := sum of last row
- diagonal = sum of matrix[i, n-1-i] for all i from 1 to n-2
- return first_row + last_row + diagonal
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): n = len(matrix) if n <= 2: return sum(sum(row) for row in matrix) first_row = sum(matrix[0]) last_row = sum(matrix[n-1]) diagonal = sum(matrix[i][n-1-i] for i in range(1, n-1)) return first_row + last_row + diagonal ob = Solution() matrix = [ [4, 3, 2], [9, 1, 8], [2, 5, 6] ] print(ob.solve(matrix))
Input
matrix = [[4, 3, 2], [9, 1, 8], [2, 5, 6]]
Output
23
- Related Articles
- Program to find number of distinct quadruple that forms target sum in python
- Swift Program to Find the Sum of the Boundary Elements of a Matrix
- Program to check some elements in matrix forms a cycle or not in python
- Program to find diagonal sum of a matrix in Python
- Swift Program to Calculate the Sum of Matrix Elements
- Python program to find sum of elements in list
- Program to find sum of unique elements in Python
- C Program to print the sum of boundary elements of a matrix
- Python Program to Print Matrix in Z form
- Program to find sum of all elements of a tree in Python
- Find the difference of the sum of list elements that are missing from Matrix and vice versa in python
- Go language Program to calculate the sum of matrix elements
- Swift Program to calculate the sum of columns of matrix elements
- Swift Program to calculate the sum of rows of matrix elements
- Golang Program to calculate the sum of columns of matrix elements

Advertisements