Created
February 14, 2022 23:38
-
-
Save aasmpro/aa7e9e84f89492ffa6c205bd35b2890c to your computer and use it in GitHub Desktop.
Python - rotate a matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for test:
rotate 1 time forward or 3 times backward:
rotate 2 times forward or backward:
rotate 3 times forward or 1 time backward:
and rotate 0 times or a full rotate: