Skip to content

Divide matrix into submatrix python

The program must accept an integer matrix of size R*C and four integers X, Y, P, Q as the input. The program must divide the matrix into nine submatrices based on the following condition. The program must divide the matrix horizontally after the Xth row and Yth row. Then the program must divide the matrix vertically after the Pth column and Qth column. Finally, the program must print the sum of integers in each submatrix as the output.

Input:

6 5

6 9 2 9 2
7 1 9 3 2
9 9 1 2 6
6 5 7 1 9
6 6 6 2 3
1 6 7 9 7

3 5 2 4 

Output:

41 26 10 23 16 12 7 16 7

Explanation:

Here X = 3, Y=5, P = 2 and Q = 4

The nine submatrices and their sums are given below. 

1st submatrix sum= 6+9+7+1+9+9 =41

6 9

7 1

9 9

2nd submatrix sum= 2+9+9+3+1+2 =26

2 9

9 3
 
1 2

3rd submatrix sum= 2+2+6 = 10

2

2

6

4th submatrix sum= 6+5+6+6 = 23

6 5

6 6

5th submatrix sum = 7+1+6+2 = 16

7 1

6 2

6th submatrix sum = 9 + 3 = 12

9

3

7th submatrix sum = 1 + 6 = 7

1 6

8th submatrix sum = 7 + 9 = 16

7 9

9th submatrix sum = 7

7

My program:

r,c=map(int,input().split())
m=[list(map(int,input().split())) for i in range(r)]
x,y,p,q=list(map(int,input().split()))

for i in range(x):
    
    for j in range(p):
        
        print(m[i][j])
        
    print()  

How to iterate from the given row and column and find the submatrix and print the sum?

Answer

Here are five solutions…

After reading all input like you did, you could go through the three boundary pairs for columns and the three boundary pairs for columns:

print(*(sum(sum(row[j:J]) for row in m[i:I])
        for i, I in [(0, x), (x, y), (y, r)]
        for j, J in [(0, p), (p, q), (q, c)]))

Same idea, slicing earlier / less often:

print(*(sum(sum(row[j:J]) for row in rows)
        for rows in [m[:x], m[x:y], m[y:]]
        for j, J in [(0, p), (p, q), (q, c)]))

Or without slicing:

print(*(sum(m[i][j]
            for i in range(*irange)
            for j in range(*jrange))
        for irange in [(0, x), (x, y), (y, r)]
        for jrange in [(0, p), (p, q), (q, c)]))

Or go through the matrix and update the right one of the nine sums:

sums = [0] * 9
for i in range(r):
    for j in range(c):
        sums[((i>=x)+(i>=y)) * 3 + (j>=p)+(j>=q)] += m[i][j]
print(*sums)

Again a variation:

sums = [0] * 9
for i in range(r):
    for j in range(c):
        sums[(0 if i<x else 3 if i<y else 6) +
             (0 if j<p else 1 if j<q else 2)] += m[i][j]
print(*sums)

Try it online!