-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path1.7-Rotate_Matrix.py
60 lines (48 loc) · 1.49 KB
/
1.7-Rotate_Matrix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# CTCI 1.7
# Rotate Matrix
import unittest
# My Solution
#-------------------------------------------------------------------------------
# CTCI Solution
def rotate_matrix(matrix):
'''rotates a matrix 90 degrees clockwise'''
n = len(matrix)
for layer in range(n // 2):
first, last = layer, n - layer - 1
for i in range(first, last):
# save top
top = matrix[layer][i]
# left -> top
matrix[layer][i] = matrix[-i - 1][layer]
# bottom -> left
matrix[-i - 1][layer] = matrix[-layer - 1][-i - 1]
# right -> bottom
matrix[-layer - 1][-i - 1] = matrix[i][- layer - 1]
# top -> right
matrix[i][- layer - 1] = top
return matrix
#-------------------------------------------------------------------------------
#Testing
class Test(unittest.TestCase):
'''Test Cases'''
data = [
([
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
], [
[21, 16, 11, 6, 1],
[22, 17, 12, 7, 2],
[23, 18, 13, 8, 3],
[24, 19, 14, 9, 4],
[25, 20, 15, 10, 5]
])
]
def test_rotate_matrix(self):
for [test_matrix, expected] in self.data:
actual = rotate_matrix(test_matrix)
self.assertEqual(actual, expected)
if __name__ == "__main__":
unittest.main()