Answer to Question #195137 in Python for sai

Question #195137

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-05-19T11:58:08-0400
def rotate(l:list, r:int):


	new_l = []
	for el in l[len(l)-r:] + l[:len(l)-r]:
		new_l.append(el)
	return new_l


def rotate_rings(matrix:list, r:int, m:int, n:int):


	tmp = []
	k = 0
	l = 0
	while (((n - k) > 0) and ((m - l) > 0)) and ((n - k)*(m-l)) > r:
		for i in range(k,n):
			tmp.append(matrix[k][i])
		for j in range(l+1,m):
			tmp.append(matrix[j][n-1])
		for i in range(n-2,k-1,-1):
			tmp.append(matrix[m-1][i])
		for j in range(m-2,l,-1):
			tmp.append(matrix[j][k])
		tmp = rotate(tmp,r)
		c = 0
		for i in range(k,n):
			matrix[k][i] = tmp[c]
			c += 1
		for j in range(l+1,m):
			matrix[j][n-1] = tmp[c]
			c += 1
		for i in range(n-2,k-1,-1):
			matrix[m-1][i] = tmp[c]
			c += 1
		for j in range(m-2,l,-1):
			matrix[j][k] = tmp[c]
			c += 1		
		tmp = []
		k += 1
		l += 1
		m -= 1
		n -= 1
	for el in matrix:
		print(*el)


while True:
	try:
		m, n = map(int,input('m n: ').split())
		matrix = []
		for i in range(m):
			tmp = list(map(int,input('{} line: '.format(i+1)).split()))
			if len(tmp) != n:
				raise ValueError
			matrix.append(tmp)


		r = int(input('r: '))


	except ValueError:
		print('incorrect input')
		continue
	rotate_rings(matrix, r, m, n)





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

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS