gpt4 book ai didi

python - 查找给定矩阵的所有子矩阵

转载 作者:太空狗 更新时间:2023-10-29 21:54:42 25 4
gpt4 key购买 nike

我需要找到给定矩阵 mxn 的所有可能子矩阵。我正在尝试在 python 中执行此操作并且不想使用 numpy。我们可以只使用循环来做到这一点吗?

例如:2x2 矩阵

Matrix = [
[1, 2],
[3, 4]
]

Submatrices =[ [1],
[1,2],
[2],
[3],
[4],
[3, 4],
[[1], [3]],
[[2],[4]],
[[1,2],[3,4]] ]

最佳答案

假设矩阵

Matrix = [
[1, 2,3],
[3, 4,5],
[5,6,7]
]

分成3个功能:

def ContinSubSeq(lst):
size=len(lst)
for start in range(size):
for end in range(start+1,size+1):
yield (start,end)

def getsubmat(mat,start_row,end_row,start_col,end_col):
return [i[start_col:end_col] for i in mat[start_row:end_row] ]

def get_all_sub_mat(mat):
rows = len(mat)
cols = len(mat[0])
for start_row,end_row in ContinSubSeq(list(range(rows))):
for start_col,end_col in ContinSubSeq(list(range(cols))):
yield getsubmat(mat,start_row,end_row,start_col,end_col)

运行这个

for i in get_all_sub_mat(Matrix):
print i

或者更简单,放在一个函数中:

def get_all_sub_mat(mat):
rows = len(mat)
cols = len(mat[0])
def ContinSubSeq(lst):
size=len(lst)
for start in range(size):
for end in range(start+1,size+1):
yield (start,end)
for start_row,end_row in ContinSubSeq(list(range(rows))):
for start_col,end_col in ContinSubSeq(list(range(cols))):
yield [i[start_col:end_col] for i in mat[start_row:end_row] ]

关于python - 查找给定矩阵的所有子矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35171721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com