# Find sum of all elements in a matrix except the elements in row and-or column of given cell 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 −

Live Demo

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]

Updated on: 19-Aug-2020

776 Views