본문 바로가기

CodeSnippet3

문자열 분리 문자열분리 * 알고리즘 문제를 풀다 보면 문자열을 일정크기로 잘라야하는 경우가 있다. def get_splits(s, split_len): return [s[i:i+split_len] for i in range(0, len(s), split_len)] text = 'asdfhlkasdfjhlasdf' print(get_splits(text, 2)) # ['as', 'df', 'hl', 'ka', 'sd', 'fj', 'hl', 'as', 'df'] print(get_splits(text, 4)) # ['asdf', 'hlka', 'sdfj', 'hlas', 'df'] print(get_splits(text, 3)) # ['asd', 'fhl', 'kas', 'dfj', 'hla', 'sdf'] 2022. 4. 25.
시뮬레이션 - 방향설정 방향바꾸기 알고리즘 문제를 풀다 보면 방향을 바꾸어야 될 필요성이 있다 현재 방향에서 왼쪽 또는 오른쪽 이때 dx, dy 를 설정하고 direction으로 방향 인덱스를 바꾼다. # 동, 북, 서, 남 # 0, 1, 2, 3 dx = [1, 0, -1, 0] dy = [0, 1, 0, -1] # 동쪽 direction = 0 dx[direction] == 1 dy[direction] == 0 # 동쪽에서 북쪽으로 왼쪽으로 방향을 바꾼다 direction += 1 dx[direction] == 0 dy[direction] == 1 # 북쪽에서 서쪽으로 왼쪽으로 방향을 바꾼다 direction += 1 dx[direction] == -1 dy[direction] == 0 # 서쪽에서 북쪽으로 오른쪽으로 방향.. 2022. 4. 21.
Rotate Matrix def rotate_matrix(grid): return list(map(list, zip(*reversed(grid)))) def print_matrix(grid): for row in grid: print(row) print('----') grid = [['1', '2'], ['.', '0']] # check original matrix print_matrix(grid) # reverse the outer list print_matrix(list(reversed(grid))) # zip the reversed list print_matrix(rotate_matrix(grid)) Ref https://stackoverflow.com/questions/53242961/rotating-a-list-of-l.. 2022. 4. 16.