
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Sum of All Elements in a Matrix Except Given Cell's Row and Column in Python
Suppose we have a 2D matrix and a set of cell indexes. Cell indices are represented as (i, j) where i is row and j is column, now, for every given cell index (i, j), we have to find the sums of all matrix elements excluding the elements present in ith row and/or jth column.
So, if the input is like
2 | 2 | 3 |
4 | 5 | 7 |
6 | 4 | 3 |
cell indices = [(0, 0), (1, 1), (0, 1)], then the output will be [19, 14, 20]
To solve this, we will follow these steps −
n := size of ind_arr
ans := a new list
-
for i in range 0 to n, do
Sum := 0
row := ind_arr[i, 0]
col := ind_arr[i, 1]
-
for j in range 0 to row count of mat, do
-
for k in range 0 to column count of map, do
-
if j is not same as row and k is not same as col, then
Sum := Sum + mat[j, k]
-
-
insert Sum at the end of ans
return ans
Example
Let us see the following implementation to get better understanding −
def show_sums(mat, ind_arr): n = len(ind_arr) ans = [] for i in range(0, n): Sum = 0 row = ind_arr[i][0] col = ind_arr[i][1] for j in range(0, len(mat)): for k in range(0, len(mat[0])): if j != row and k != col: Sum += mat[j][k] ans.append(Sum) return ans mat = [[2, 2, 3], [4, 5, 7], [6, 4, 3]] ind_arr = [(0, 0),(1, 1),(0, 1)] print(show_sums(mat, ind_arr))
Input
mat = [[2, 2, 3], [4, 5, 7], [6, 4, 3]] ind_arr = [(0, 0),(1, 1),(0, 1)
Output
[19, 14, 20]