-
행렬과 연산코딩 테스트/Level 4 2022. 12. 24. 21:45반응형
https://school.programmers.co.kr/learn/courses/30/lessons/118670
level 2 수준으로 풀어봄..
당연히 통과는 불가능.from copy import deepcopy def shift_row(a: list) -> list: return a[-1:] + a[:-1] def rotate(a: list) -> list: b = deepcopy(a) b[0] = a[1][:1] + a[0][:-1] b[-1] = a[-1][1:] + a[-2][-1:] for i in range(1, len(a) - 1): b[i][0] = a[i + 1][0] b[i][-1] = a[i - 1][-1] return b def solution(rc, operations): for operation in operations: if operation == 'Rotate': rc = rotate(rc) else: rc = shift_row(rc) return rc
디큐(양방향 링크드 리스트)를 이용해서..
def solution(rc, operations): def shift_row(): col1.appendleft(col1.pop()) col2.appendleft(col2.pop()) if len(rc[0]) > 2: rows.appendleft(rows.pop()) def rotate(): if len(rc[0]) > 2: col1.append(rows[-1].popleft()) rows[0].appendleft(col1.popleft()) col2.appendleft(rows[0].pop()) rows[-1].append(col2.pop()) else: col1.append(col2.pop()) col2.appendleft(col1.popleft()) from collections import deque col1, col2, rows = deque(), deque(), deque() for each in rc: col1.append(each[0]) col2.append(each[-1]) if len(rc[0]) > 2: rows.append(deque(each[1:-1])) for operation in operations: if operation == 'Rotate': rotate() else: shift_row() for i in range(len(rc)): rc[i][0] = col1[i] rc[i][-1] = col2[i] if len(rc[0]) > 2: for j in range(1, len(rc[0]) - 1): rc[i][j] = rows[i][j - 1] return rc
약간 정리한다면..
def solution(rc, operations): def shift_row(): col1.appendleft(col1.pop()) col2.appendleft(col2.pop()) rows.appendleft(rows.pop()) def rotate(): if len(rc[0]) > 2: col1.append(rows[-1].popleft()) rows[0].appendleft(col1.popleft()) col2.appendleft(rows[0].pop()) rows[-1].append(col2.pop()) else: col1.append(col2.pop()) col2.appendleft(col1.popleft()) from collections import deque col1, col2, rows = deque(), deque(), deque() for each in rc: col1.append(each[0]) col2.append(each[-1]) rows.append(deque(each[1:-1])) for operation in operations: if operation == 'Rotate': rotate() else: shift_row() for i in range(len(rc)): rc[i][0] = col1[i] rc[i][-1] = col2[i] for j in range(1, len(rc[0]) - 1): rc[i][j] = rows[i][j - 1] return rc
줄 줄이기에 몰두해 본다면..
def solution(rc, operations): from collections import deque col1, col2, rows = deque(), deque(), deque() for each in rc: col1.append(each[0]) col2.append(each[-1]) rows.append(deque(each[1:-1])) for operation in operations: if operation == 'Rotate': if len(rc[0]) > 2: col1.append(rows[-1].popleft()) rows[0].appendleft(col1.popleft()) col2.appendleft(rows[0].pop()) rows[-1].append(col2.pop()) else: col1.append(col2.pop()) col2.appendleft(col1.popleft()) else: col1.appendleft(col1.pop()) col2.appendleft(col2.pop()) rows.appendleft(rows.pop()) rc = [] for left, mid, right in zip(col1, rows, col2): rc.append([left] + list(mid) + [right]) return rc
반응형