"Livre pour former des compétences en programmation pour combattre dans le monde" Exemple de solution de code Python - 1.7 Rotation de matrice
import numpy as np
def rotate(matrix):
if matrix.ndim == 0 or matrix.shape[0] != matrix.shape[1]:
return False
n = matrix.shape[0]
for layer in range(0,int(n/2)):
first = layer
last = n-1-layer
for i in range(first,last):
offset = i - first
top = matrix[first,i]
matrix[first,i] = matrix[last-offset,first]
matrix[last-offset,first] = matrix[last,last-offset]
matrix[last,last-offset] = matrix[i,last]
matrix[i,last] = top
return True
input_matrix_1 = np.matrix([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
print(input_matrix_1)
print(rotate(input_matrix_1))
print(input_matrix_1)
input_matrix_2 = np.matrix([[1,2,3],[4,5,6],[7,8,9]])
print(input_matrix_2)
print(rotate(input_matrix_2))
print(input_matrix_2)
Recommended Posts