将矩阵划分为子矩阵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()
如何从给定的行和列迭代并找到子矩阵并打印总和?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里有五个解决方案...
像您一样阅读所有输入后,您可以遍历列的三个边界对和列的三个边界对:
相同的想法,更早/更少地切片:
或者不切片:
或者遍历矩阵并更新九个总和中正确的一个:
再次是一种变体:
在线试用!
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:
Same idea, slicing earlier / less often:
Or without slicing:
Or go through the matrix and update the right one of the nine sums:
Again a variation:
Try it online!