加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 22:51:49 所属栏目:Python 来源:网络整理
导读:我需要找到给定矩阵mxn的所有可能的子矩阵.我试图在python中这样做,不想使用numpy.我们可以只使用循环吗? 例如:22矩阵 Matrix = [ [1,2],[3,4] ]Submatrices =[ [1],[1,[2],[3],[4],4],[[1],[3]],[[2],[4]],[[1,4]] ] 最佳答案 假设矩阵 Matrix = [ [1,2,3

我需要找到给定矩阵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] ]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读