- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 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 −
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]
- Related Articles
- Program to find number of elements in matrix follows row column criteria in Python
- How to find the sum of all elements of a given matrix using Numpy?
- To print all elements in sorted order from row and column wise sorted matrix in Python
- Maximum sum of elements from each row in the matrix in C++
- Program to find a list of product of all elements except the current index in Python
- Find sum of frequency of given elements in the list in Python
- How to find the sum of all elements of a given array in JavaScript?
- Find distinct elements common to all rows of a matrix in Python
- How to find the variance of row elements of a matrix in R?
- Program to find sum of all elements of a tree in Python
- How to find the row and column index for upper triangular matrix elements in R?
- Program to find valid matrix given row and column sums in Python
- Find the original matrix when largest element in a row and a column are given in Python
- How to find all elements in a given array except for the first one using JavaScript?
- Python - Merge a Matrix by the Elements of First Column
