] def optimrcs(mx,rows = [],cols = []): 如果不是行或不是cols:return 0,[],[] maxscore = 0 行中r的: 如果不是mx [r] .count(1) :对于col中的c,继续 : 如果不是mx [r] [c]:继续 #eval column submatrix vs row submatrix colsxthis = cols [:]; colsxthis.remove(c) colscore,rset,cset = optimrcs(mx,rows,colsxthis) 如果colscore> maxscore: maxscore ,maxrows,maxcols = colscore,rset,cset rowsxthis = rows [:]; rowsxthis.remove(r) rowscore,rset,cset = optimrcs(mx,rowsxthis,cols) if rowscore> = maxscore: maxscore,maxrows,maxcols = rowscore,rset,cset 如果不是maxscore: 返回len(行)* len(cols),行,cols 返回maxscore,maxrows,maxcols if __name__ ==''__ main__'': 得分,rowsel,colsel = optimrcs(X,范围(5),范围(5)) 打印''得分=%s,行=%s,cols =%s''%(得分,rowsel,colsel) 打印 范围内的r(5): row = X [r] 范围内的c(5): 如果r在rowsel中,c在colsel中: print''<%s>''%row [c], else : 打印''%s''%行[c], 打印 =========== ======================================= == 跑步结果因此: [21:24] C:\ pywk \ clp> submatrix.py 得分= 16,行= [1, 2,3,4],cols = [ 0,1,3,4] 1 0 0 0 1 < 0> &℃,GT; 0< 0> < 0> < 0> &℃,GT; 0< 0> < 0> < 0> &℃,GT; 0< 0> < 0> < 0> &℃,GT; 1< 0> < 0> 问候, Bengt Richter Brute force seems to work on this little example. Maybe it canbe memoized and optimized and/or whatever to handle your larger matrix fast enough? ====< submatrix.py >================================X = [[1, 0, 0, 0, 1],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[0, 0, 0, 0, 0],[0, 0, 1, 0, 0]] def optimrcs(mx, rows=[], cols=[]):if not rows or not cols: return 0,[],[]maxscore = 0for r in rows:if not mx[r].count(1): continuefor c in cols:if not mx[r][c]: continue# eval column submatrix vs row submatrixcolsxthis = cols[:]; colsxthis.remove(c)colscore, rset, cset = optimrcs(mx, rows, colsxthis)if colscore>maxscore:maxscore, maxrows, maxcols = colscore, rset, csetrowsxthis = rows[:]; rowsxthis.remove(r)rowscore, rset, cset = optimrcs(mx, rowsxthis, cols)if rowscore >= maxscore:maxscore, maxrows, maxcols = rowscore, rset, csetif not maxscore:return len(rows)*len(cols), rows, colsreturn maxscore, maxrows,maxcols if __name__ == ''__main__'':score, rowsel, colsel = optimrcs(X, range(5), range(5))print ''Score = %s, rows = %s, cols = %s'' % (score,rowsel,colsel)printfor r in range(5):row = X[r]for c in range(5):if r in rowsel and c in colsel:print ''<%s>''% row[c],else:print '' %s ''% row[c],print================================================== ==Running it results thus: [21:24] C:\pywk\clp>submatrix.pyScore = 16, rows = [1, 2, 3, 4], cols = [0, 1, 3, 4] 1 0 0 0 1<0> <0> 0 <0> <0><0> <0> 0 <0> <0><0> <0> 0 <0> <0><0> <0> 1 <0> <0> Regards,Bengt Richter 这篇关于得到一个真正的子矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-24 10:44