「世界で闘うプログラミング力を鍛える本」Pythonコード解答例 - 1.7 行列の回転
#目次
###CHAP1. 配列と文字列
#Pythonコード解答例
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)