Menu Close

Shift the K elements of each row to right of the matrix

Given a square matrix and a number k. The task is to shift the first k elements of each row to the right of the matrix.

Input:
Matrx[N][N] = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]]
k = 2


Output:
Matrx[N][N] = [[3, 1, 2]
               [6, 4, 5]
               [9, 7, 8]]
def shiftMatrx(Matrx,K):
    if(K>len(Matrx)):
        print("Shifting Not Possible!!!")
        return
    i,L=0,[]
    while(i<len(Matrx)):
        temp=[]
        for j in range(K,len(Matrx)):
            temp.append(Matrx[i][j])
        for j in range(0,K):
            temp.append(Matrx[i][j])
        i+=1
        L.append(temp)
    return L


#Driver
'''
Matrx = [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9, 10, 11, 12],
        [13, 14, 15, 16]
    ]
'''
Matrx=[]
while True:
    arr=list(map(str,input().split(" ")))
    if arr != ['']:
        Matrx.append(list(map(int,arr)))
    else:
        break
K=int(input("K: "))

S_Matx = shiftMatrx(Matrx,K)
for i in S_Matx:
    print (i)

INPUT_1:
1  2  3
4  5  6
7  8  9

K:  2

OUTPUT:
[3,  1,  2]
[6,  4,  5]
[9,  7,  8]


INPUT_2:
1  2  3  4
5  6  7  8 
9  10  11  12
13  14  15  16

K:  2

OUTPUT:
[3,  4,  1,  2]
[7,  8,  5,  6]
[11,  12,  9,  10]
[15,  16,  13,  14]


ILLUSTRATION

EXECUTED USING LINUX TERMINAL PYTHON3

Morae Q!