Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Check if sums of i-th row and i-th column are same in matrix in Python
In matrix operations, we often need to compare row and column sums. This problem asks us to check if the sum of the i-th row equals the sum of the i-th column for any row-column pair in a given matrix.
Problem Understanding
Given a matrix, we need to verify if there exists at least one index i where the sum of row i equals the sum of column i.
For the example matrix:
| 2 | 3 | 4 | 5 |
| 10 | 6 | 4 | 2 |
| 1 | 4 | 6 | 7 |
| 1 | 5 | 6 | 7 |
Row 0 sum = 2 + 3 + 4 + 5 = 14
Column 0 sum = 2 + 10 + 1 + 1 = 14
Since they match, the function returns True.
Algorithm Steps
- Get matrix dimensions (rows and columns)
- For each row index i:
- Calculate sum of row i
- Calculate sum of column i
- If sums are equal, return True
- If no matching pair found, return False
Implementation
def solve(mat):
row = len(mat)
col = len(mat[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
# Test with the given matrix
matrix = [
[2, 3, 4, 5],
[10, 6, 4, 2],
[1, 4, 6, 7],
[1, 5, 6, 7]
]
print(solve(matrix))
True
Alternative Implementation Using Built-in Functions
We can simplify the solution using Python's sum() function ?
def solve_optimized(mat):
rows = len(mat)
for i in range(rows):
row_sum = sum(mat[i])
col_sum = sum(mat[j][i] for j in range(rows))
if row_sum == col_sum:
return True
return False
# Test with another example
matrix2 = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(solve_optimized(matrix2))
False
Complete Example with Multiple Test Cases
def check_row_column_sum(matrix):
"""Check if any row sum equals corresponding column sum"""
rows = len(matrix)
for i in range(rows):
row_sum = sum(matrix[i])
col_sum = sum(matrix[j][i] for j in range(rows))
print(f"Row {i} sum: {row_sum}, Column {i} sum: {col_sum}")
if row_sum == col_sum:
return True
return False
# Test cases
test_matrix = [
[2, 3, 4, 5],
[10, 6, 4, 2],
[1, 4, 6, 7],
[1, 5, 6, 7]
]
result = check_row_column_sum(test_matrix)
print(f"Result: {result}")
Row 0 sum: 14, Column 0 sum: 14 Result: True
Conclusion
This algorithm efficiently checks if any row sum matches its corresponding column sum by iterating through each row-column pair. The time complexity is O(n²) where n is the matrix dimension, making it suitable for moderate-sized matrices.
