Answer to Question #176332 in Python for phani

Question #176332
Rotate Matrix Rings
Given a matrix of order M*N and a value K, write a program to rotate each ring of the matrix clockwise by K elements. If in any ring has less than or equal to K elements, then don’t rotate that ring.
Input

The first line of input will be two space-separated integers, denoting the M and N.
The next M lines will contain N space-separated integers.
The next line will contain an integer, denoting K.
Output
The output should be M*N matrix by rotating the matrix by K elements.
Explanation
Therefore, by rotating each ring in clockwise direction by 3 elements will give (13, 9, 5, 1, 2, 3, 4, 8, 12, 16, 15, 14) and (10, 6, 7, 11). So the output should be
4 8 12 16
3 10 6 15
2 7 11 14
1 5 9 13
Sample Input 1
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
3

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

Sample Input 2
3 4
1 2 3 4
10 11 12 5
9 8 7 6
2
Sample Output 2
9 10 1 2
8 11 12 3
7 6 5 4
1
Expert's answer
2021-03-31T22:53:55-0400
M, N = input().split(' ')
M, N = int(M), int(N)
matrix = []
for _ in range(M):
	row = [int(x) for x in input().split(' ')]
	matrix.append(row)


K = int(input())


values = matrix[0][:-1] + [x[-1] for x in matrix][:-1] + matrix[-1][::-1][:-1] + [x[0] for x in matrix][::-1][:-1]


values = values[-K:] + values[:-K]
print(values)


output = matrix


idxs = [(0, j) for j in range(N)][:-1] + [(i, N - 1) for i in range(M)][:-1] + [(M - 1, j) for j in range(N)][::-1][:-1] + [(i, 0) for i in range(M)][::-1][:-1]


idx = 0
for i, j in idxs:
	output[i][j] = values[idx]
	idx += 1


print(output)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Assignment Expert
15.04.21, 14:08

Dear nagaraju, Questions in this section are answered for free. We can't fulfill them all and there is no guarantee of answering certain question but we are doing our best. And if answer is published it means it was attentively checked by experts. You can try it yourself by publishing your question. Although if you have serious assignment that requires large amount of work and hence cannot be done for free you can submit it as assignment and our experts will surely assist you.

nagaraju
15.04.21, 09:20

sample input 1: 4 0 5 1 0 2 10 3 6 3 0 1 1 2 2 4 sample output: 6x^3 + 14x^2 + 2x + 6 sample input 2: 4 0 5 1 0 2 10 3 6 4 0 -5 1 0 2 -10 3 -6 sample output: 0 is expected

nagaraju
15.04.21, 09:01

The out put is different as sample output 1 and 2

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS