Skip to content

Commit 88430c6

Browse files
solution for rotate matrix
1 parent 7c17bd3 commit 88430c6

File tree

2 files changed

+45
-0
lines changed
  • Python/chapter01

2 files changed

+45
-0
lines changed

Python/chapter01/1.6 - String Compression/Nick.py

100644100755
File mode changed.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/python3
2+
import random
3+
from pprint import pprint
4+
5+
def build_matrix(w, h, max=10):
6+
'''function that builds a matrix with random numbers including 0'''
7+
return [[random.randint(0, max) for _ in range(w)] for _ in range(h)]
8+
9+
def rotate_matrix(matrix):
10+
'''function that rotates a matrix clockwise'''
11+
if (len(matrix) is 0 or len(matrix) is not len(matrix[0])): return False
12+
matrix_length = len(matrix)
13+
for layer in range(matrix_length//2):
14+
first = layer
15+
last = matrix_length - 1 - layer
16+
for i in range(first, last):
17+
offset = i - first
18+
top = matrix[first][i]
19+
20+
######################
21+
# a ----------> d #
22+
# ^ | #
23+
# | | #
24+
# | | #
25+
# | v #
26+
# b <------------ c #
27+
#######################
28+
29+
# top left inherits from bottom bottom left
30+
matrix[first][i] = matrix[last - offset][first]
31+
32+
# bottom left becomes bottom right
33+
matrix[last - offset][first] = matrix[last][last - offset]
34+
35+
# bottom right becomes top right
36+
matrix[last][last - offset] = matrix[i][last]
37+
38+
# top right becomes top left
39+
matrix[i][last] = top
40+
41+
if __name__ =='__main__':
42+
matrix = build_matrix(5, 5)
43+
pprint(matrix)
44+
rotate_matrix(matrix)
45+
pprint(matrix)

0 commit comments

Comments
 (0)