how to write the matrix rotation program
def rotate_matr(m:list, n:int, clockwise=True):
'''a function that rotates the matrix 'm' 'n' times by 90'
if clockwise=True and by -90' if clockwise=False'''
if clockwise:
for i in range(n):
m = [*zip(*m)]
for j in range(len(m)):
m[j] = list(reversed(m[j]))
else:
for i in range(n):
for j in range(len(m)):
m[j] = list(reversed(m[j]))
m = [*zip(*m)]
for j in range(len(m)):
m[j] = list(m[j])
return m
#input of matrix dimension
r, c = input('matrix dimension ').split()
r, c = int(r), int(c)
matrix = []
#input matrix
for i in range(r):
matrix.append(list(map(int, input().split())))
#input of the number of matrix rotations by 90'
n = int(input('turns '))
#direction of rotation input
c = int(input('direction (1 or -1) '))
if c == 1:
c = True
else:
c = False
print(*rotate_matr(matrix, n, c), sep='\n')
Comments
Leave a comment