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

前端之家收集整理的这篇文章主要介绍了python – 查找给定矩阵的所有子矩阵前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我需要找到给定矩阵mxn的所有可能的子矩阵.我试图在python中这样做,不想使用numpy.我们可以只使用循环吗?

例如:2×2矩阵

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

Submatrices =[ [1],[1,[2],[3],[4],4],[[1],[3]],[[2],[4]],[[1,4]] ] 
最佳答案
假设矩阵

Matrix = [
      [1,2,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,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相关文章