Algorithm/tool

[python] 행렬의 좌/우회전, 전치행렬 간단한 코드

Viator 2023. 3. 17. 19:29

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]]