# Rotate Matrix using Python

This is my solution to Exercise 1.7 from Cracking the Coding Interview. I would appreciate any feedback on coding style and algorithm efficiency.

I do know that there is an existing function in numpy for rotating a matrix, however I am trying to implement this as an exercise.

The problem statement follows:

Given an image represented by an NxN matrix where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place?

import unittest

def rotate_square_matrix_right_90(matrix: list) -> list:
"""Rotate an NxN matrix 90 degrees clockwise."""
n = len(matrix)
for layer in range((n + 1) // 2):
for index in range(layer, n - 1 - layer, 1):
matrix[layer][index], matrix[n - 1 - index][layer], \
matrix[index][n - 1 - layer], matrix[n - 1 - layer][n - 1 - index] = \
matrix[n - 1 - index][layer], matrix[n - 1 - layer][n - 1 - index], \
matrix[layer][index], matrix[index][n - 1 - layer]
return matrix

class MyTest(unittest.TestCase):
def test_rotate_matrix_right_90(self):
input_matrix = [[0, 2, 4, 6], [-1, 1, 3, 5], [-2, 0, 2, 4], [-3, -1, 1, 3]]
correct_rotated_matrix = [[-3, -2, -1, 0], [-1, 0, 1, 2], [1, 2, 3, 4], [3, 4, 5, 6]]
self.assertSequenceEqual(rotate_square_matrix_right_90(input_matrix), correct_rotated_matrix)

if __name__ == "__main__":
unittest.main()


You can use much simpler algorithm in python: Transpose matrix:

zip(*matrix)


Inverse rows in transposed matrix (equals rotation right):

list(list(x)[::-1] for x in zip(*matrix))


However, if you want to rotate left, you need first inverse rows and then transpose, which is slightly more code.

• To rotate left side, list(list(x) for x in zip(*matrix))[::-1] – jayko03 Jul 25 '17 at 19:37