Created
May 2, 2021 18:25
-
-
Save DepthDeluxe/0fcbfee2d7091423f4da46f2edb74d42 to your computer and use it in GitHub Desktop.
1.7 CTCI
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
even_matrix = [ | |
[ 0, 1, 2, 3 ], | |
[ 4, 5, 6, 7 ], | |
[ 8, 9, 10, 11 ], | |
[ 12, 13, 14, 15 ] | |
] | |
odd_matrix = [ | |
[ 0, 1, 2, 3, 4 ], | |
[ 5, 6, 7, 8, 9 ], | |
[ 10, 11, 12, 13, 14 ], | |
[ 15, 16, 17, 18, 19 ], | |
[ 20, 21, 22, 23, 24 ] | |
] | |
def _validate_input(matrix): | |
size = len(matrix) | |
for row in matrix: | |
if len(row) != size: | |
raise ValueError('Input matrix is not NxN!') | |
''' | |
Rotates an NxN matrix by 90 degrees | |
''' | |
def rotate(matrix): | |
_validate_input(matrix) | |
size = len(matrix) | |
for row_index in range(size): | |
for column_index in range(row_index): | |
buffer = matrix[row_index][column_index] | |
matrix[row_index][column_index] = matrix[column_index][row_index] | |
matrix[column_index][row_index] = buffer | |
return matrix | |
def print_matrix(matrix): | |
for row in matrix: | |
print(row) | |
if __name__ == '__main__': | |
print_matrix(rotate(even_matrix)) | |
print('') | |
print_matrix(rotate(odd_matrix)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment