numpy 같은 라이브러리 없이도 행렬의 회전, 전치행렬에 대해서 한 줄로 간단하게 변환시킬 수 있어서 함수로 작성해 여기에 기록해둔다.
def rotate(M, dir='left'):
if dir == 'left': # left 90 degree rotate
out = list(reversed(list(map(list, zip(*M)))))
elif dir == 'right': # right 90 degree rotate
out = list(map(list, zip(*reversed(M))))
elif dir == 'transpose': # transpose matrix
out = list(map(list, zip(*M)))
else:
print('choose dir "left"/"right"/"transpose"')
return out
M = [[1,2,3,4],
[5,6,7,8]]
print(rotate(M, dir='left')) # [[4, 8], [3, 7], [2, 6], [1, 5]]
print(rotate(M, dir='right')) # [[5, 1], [6, 2], [7, 3], [8, 4]]
print(rotate(M, dir='transpose')) # [[1, 5], [2, 6], [3, 7], [4, 8]]
'Algorithm > tool' 카테고리의 다른 글
[python] 계층적 구조의 다중 필터링 (0) | 2023.02.08 |
---|---|
[python] 리스트 내 요소들 크기 순위 매기기 (0) | 2023.02.08 |