将矩阵划分为子矩阵 python

Divide matrix into submatrix python

程序必须接受大小为 R*C 的整数矩阵和四个整数 X、Y、P、Q 作为输入。程序必须根据以下条件将矩阵划分为九个子矩阵。程序必须在第 X 行和第 Y 行之后水平划分矩阵。然后程序必须在第 P 列和第 Q 列之后垂直划分矩阵。最后,程序必须打印每个子矩阵中的整数之和作为输出。

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

我的程序:


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()  

如何从给定的行和列迭代并找到子矩阵并打印总和?

这里有五个解决方案...

像您一样读取所有输入后,您可以遍历列的三个边界对和列的三个边界对:

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)]))

同样的想法,更早/更少切片:

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)]))

或不切片:

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)]))

或者遍历矩阵并更新九个和中右边的一个:

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)

再次变体:

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!