
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find matrix for which rows and columns holding sum of behind rows and columns in Python
Suppose we have a given matrix, We have to find a new matrix res, whose dimension is same as the given matrix where each element in res[i, j] = sum of the elements of matrix[r, c] for each r ≤ i, and c ≤ j.
So, if the input is like
8 | 2 |
7 | 4 |
then the output will be
8 | 10 |
15 | 21 |
To solve this, we will follow these steps −
if matrix is empty, then
return matrix
R := row count of matrix
C := column count of matrix
for r in range 1 to R - 1, do
for c in range 0 to C - 1, do
matrix[r, c] := matrix[r, c] + matrix[r - 1, c]
for r in range 0 to R - 1, do
for c in range 1 to C - 1, do
matrix[r, c] := matrix[r, c] + matrix[r, c - 1]
return matrix
Example
Let us see the following implementation to get better understanding
def solve(matrix): if not matrix: return matrix R, C = len(matrix), len(matrix[0]) for r in range(1, R): for c in range(C): matrix[r][c] += matrix[r - 1][c] for r in range(R): for c in range(1, C): matrix[r][c] += matrix[r][c - 1] return matrix matrix = [ [8, 2], [7, 4] ] print(solve(matrix))
Input
[[8, 2],[7, 4]]
Output
[[8, 10], [15, 21]]
- Related Articles
- How to multiply a matrix columns and rows with the same matrix rows and columns in R?
- C program to sort all columns and rows of matrix
- How to find the sum of rows, columns, and total in a matrix in R?
- How to find the sum of rows and columns of a given matrix using Numpy?
- How to shuffle columns or rows of matrix in PyTorch?
- Difference between Rows and Columns
- Flip Columns For Maximum Number of Equal Rows in Python
- Write a Python program to find the mean absolute deviation of rows and columns in a dataframe
- How to divide matrix rows by number of columns in R?
- Finding the number of rows and columns in a given matrix using Numpy
- Finding index of rows and columns in SAP
- Python Pandas - Select a subset of rows and columns combined
- How to display notnull rows and columns in a Python dataframe?
- Count rows/columns with sum equals to diagonal sum in C++
- Python Pandas – Count the rows and columns in a DataFrame

Advertisements