Skip to content

Instantly share code, notes, and snippets.

@aasmpro
Created February 14, 2022 23:38
Show Gist options
  • Save aasmpro/aa7e9e84f89492ffa6c205bd35b2890c to your computer and use it in GitHub Desktop.
Save aasmpro/aa7e9e84f89492ffa6c205bd35b2890c to your computer and use it in GitHub Desktop.
Python - rotate a matrix
def rotate_matrix(matrix, times):
times = times % 4
if times == 0:
# a full rotation or none
return matrix
elif times == 1:
# for 90 forward or 270 backward
return [i[::-1] for i in zip(*matrix)]
elif times == 2:
# for 180 forward or backward
return [i[::-1] for i in matrix[::-1]]
elif times == 3:
# for 270 forward or 90 backward
return list(zip(*[i[::-1] for i in matrix]))
@aasmpro
Copy link
Author

aasmpro commented Feb 14, 2022

for test:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

rotate 1 time forward or 3 times backward:

>>> print(rotate_matrix(matrix, 1))
[(7, 4, 1), (8, 5, 2), (9, 6, 3)]
>>> print(rotate_matrix(matrix, -3))
[(7, 4, 1), (8, 5, 2), (9, 6, 3)]

rotate 2 times forward or backward:

>>> print(rotate_matrix(matrix, 2))
[[9, 8, 7], [6, 5, 4], [3, 2, 1]]
>>> print(rotate_matrix(matrix, -2))
[[9, 8, 7], [6, 5, 4], [3, 2, 1]]

rotate 3 times forward or 1 time backward:

>>> print(rotate_matrix(matrix, 3))
[(3, 6, 9), (2, 5, 8), (1, 4, 7)]
>>> print(rotate_matrix(matrix, -1))
[(3, 6, 9), (2, 5, 8), (1, 4, 7)]

and rotate 0 times or a full rotate:

>>> print(rotate_matrix(matrix, 0))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(rotate_matrix(matrix, 4))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(rotate_matrix(matrix, -4))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(rotate_matrix(matrix, 8))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> print(rotate_matrix(matrix, -8))
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment