pythonnumpymatrixsubmatrix

How to extract all K*K submatrix of matrix with or without NumPy?


This is my input:

row=6 col=9

6
9
s b k g s y w g f
r g y e q j j a s
s m s a s z s l e
u s q u e h s s s
g s f h s s e s g
x d r h g y s s s

This is my code:

r=int(input())
c=int(input())
n=min(r,c)
k=3
matrix=[list(map(str,input().split())) for i in range(r)]
t = []
for i in range(0,n-1,k):
  for j in range(0,n-1,k):
    t.append([matrix[i+ii][j+jj] for ii in range(k) for jj in range(k)])
print(t) 

output got:

[['s', 'b', 'k', 'r', 'g', 'y', 's', 'm', 's'], ['g', 's', 'y', 'e', 'q', 'j', 'a', 's', 'z'], ['u', 's', 'q', 'g', 's', 'f', 'x', 'd', 'r'], ['u', 'e', 'h', 'h', 's', 's', 'h', 'g', 'y']]

this code not printing my last 3 columns why? Please help me


Solution

  • r=int(input())
    c=int(input())
    n=min(r,c)
    k=3
    matrix=[list(map(str,input().split())) for i in range(r)]
    t = []
    a=[]
    for i in range(0,r,k):
      for j in range(0,c,k):
        t.append([matrix[i+ii][j+jj] for ii in range(k) for jj in range(k)])
    print(t) 
    

    In for loop you used n variable in range. so it will end in the minimum of row and col .That's why you got error..Thank you