9
\$\begingroup\$

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()
asked Sep 18, 2016 at 8:03
\$\endgroup\$

1 Answer 1

7
\$\begingroup\$

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.

answered Sep 19, 2016 at 9:42
\$\endgroup\$
2
  • 4
    \$\begingroup\$ To rotate left side, list(list(x) for x in zip(*matrix))[::-1] \$\endgroup\$ Commented Jul 25, 2017 at 19:37
  • \$\begingroup\$ Try it online from my sample code: Rotate left, rotate right: trinket.io/python/f7ad7f9864 \$\endgroup\$ Commented Jun 10, 2020 at 21:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.