Check if sums of i-th row and i-th column are same in matrix in Python

PythonServer Side ProgrammingProgramming

Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a 2D matrix. We have to check whether the sum of i-th row is same as the sum of i-th column or not.

So, if the input is like

 2 3 4 5 10 6 4 2 1 4 6 7 1 5 6 7

then the output will be True, as the sum of first row and column is (2 + 3 + 4 + 5) = 14 and (2 + 10 + 1 + 1) = 14.

To solve this, we will follow these steps −

• row := row count of mat
• col := column count of mat
• total_row := 0, total_col := 0
• for i in range 0 to row - 1, do
• total_row := 0, total_col := 0
• for j in range 0 to col - 1, do
• total_row := total_row + mat[i, j]
• total_col := total_col + mat[j, i]
• if total_row is same as total_col, then
• return True
• return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

def solve(mat):
row = len(mat)
col = len(mat[0])
total_row = 0
total_col = 0
for i in range(row):
total_row = 0
total_col = 0
for j in range(col):
total_row += mat[i][j]
total_col += mat[j][i]

if total_row == total_col:
return True

return False

matrix = [
[2,3,4,5],
[10,6,4,2],
[1,4,6,7],
[1,5,6,7]
]

print(solve(matrix))

Input

[
[1,2,3,4],
[9,5,3,1],     [0,3,5,6],
[0,4,5,6]]

Output

True
Updated on 15-Jan-2021 06:22:35