practivceAlgorithm 570

[자료구조] 파이썬으로 LRU cache O(1) 구현하기

LRU cache O(1) 캐시는 불필요한 통신을 줄이고 기민한 UX를 제공 DB과부하를 막음.(query결과 저장) Proxy, CDN(유저와 가까운 CDN node) 메모이제이션 OrderedDict이용 from collections import OrderedDict MAX_SIZE = 2 cache = OrderedDict() def get_user(user_id): if user_id in cache: cache.move_to_end(user_id) return cache[user_id] if len(cache) == MAX_SIZE: cache.popitem(last=False) cache[user_id] = fetch_user(user_id) return cache[user_id] last=F..

[Python] Python List, Dictionary, Set등 참조형 자료구조 복사

Python의 List와 Set, Dictionary등은 call by reference한다. 즉 a = [1, 2, 3] b = a b.append(4) print(a) # [1, 2, 3, 4] 할당 된 주소가 공유된다. 때문에 자료형 a 와 동일한 자료형 b를 만들기 위해 다음과 같은 방법을 사용할 수 있다. from copy import copy, deepcopy l = [1, 2, 3] s = {1, 2, 3} d = {1:1, 2:2, 3:3} # use copy(얕은복사) l_copy = copy(l) s_copy = copy(s) d_copy = copy(d) # use deepcopy(깊은 복사) l_deepcopy = deepcopy(l) s_deepcopy = deepcopy(s) d..

[백준][Python] 17825 주사위 윷놀이

움직이는 말의 조합 2^20승에 대해 각각 10번의 이동을 조사하며 point연산. 중요로직은 section을 나누어 이동시키는 것.(shortcut) 이미 말이 있는경우 불가능처리시키는 것. import sys input = sys.stdin.readline def calculate(): global result # 각 플레이어의 구간, 위치정보 players = [[0, 0] for _ in range(5)] # 각 경우의 수에서 포인트의 합 sum_points = 0 # 1턴 부터 10턴까지 실행. for i in range(1, 11): now = turns[i] section, pos = players[now] if section == -1: return else: pos += dice[i] #..

[BOJ][Python] 17822 원판돌리기

오랜만에 구현문제를 풀어보았습니다. 회전은 k를 M주기로 나눈 나머지만큼 한번에 돌렸고 회전이 끝난 후엔 각 지점을 bfs로 추적하며 같은 부분을 제거시켰으며 제거가 없는 시점에서는 각 부분을 조사해 평균치보다 크거나 작으면 보정치를 증감해주었습니다. import sys input = sys.stdin.readline from collections import deque def rotate(i, d): new_board = [] if d: for n in range(k, M): new_board.append(round_boards[i][n]) for n in range(k): new_board.append(round_boards[i][n]) else: for n in range(M - k, M): new..

[백준][Python] 18869 멀티버스 : 좌표압축

hashmap에 tuple로 조합수를 구하는 것까지는 접근했는데 set으로 압축시키는 것은 생각을 못했음. 이러면 결국 tuple에 각 순위값이 들어가게 되는데 동일한 요소의 경우 묶여서 사라지기때문에 순위값의 갯수가 적어져 일일히 비교할 필요가 없어짐. 정렬과 indexing을 같이 사용해서 크기 비교를 해야할 때 유용하게 쓸 수 있을 것으로 보임 import sys input = sys.stdin.readline from collections import defaultdict m, n = map(int, input().split()) universe = defaultdict(int) for _ in range(m): planets = list(map(int, input().split())) keys ..

[백준][Python] 17837 새로운게임2

위에서 옮기는 것의 순서만 잘 조절해주면 나머지는 색에 따라 구분만 해주면 된다. import sys input = sys.stdin.readline def move_white(x, y, nx, ny): now = chess[x][y].index(coin) top = len(chess[x][y]) for i in range(now, top): coins[chess[x][y][i]][0] = nx coins[chess[x][y][i]][1] = ny chess[nx][ny].append(chess[x][y][i]) for _ in range(top - now): chess[x][y].pop() def move_red(x, y, nx, ny): now = chess[x][y].index(coin) top =..

[백준][Python] 21610 마법사상어와 비바라기

움직인 구름의 경우 추후 제외하고 구름을 생성하기 위해 set으로 관리. 움직이기 전 구름은 list로 뺐다 넣었다 하면서 관리. 이동은 N의 나머지로 관리 import sys input = sys.stdin.readline N, M = map(int, input().split()) A = [list(map(int, input().split())) for _ in range(N)] moves = [tuple(map(int, input().split())) for _ in range(M)] delta = ((0, 0), (0, -1), (-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1)) check = ((-1, 1), (1, 1), (-1, -1),..

[백준][Python] 17779 게리멘더링2

단순히 영역을 나누는 문제였습니다. 대각선에 대해 4번 범위 설정이 필요한 문제였습니다. 핵심은 1개씩 늘어나거나 줄어드는 dx, dy설정을 어떻게 할 것인가? 결국 i에서 i의 초깃값을 빼주면 0부터 시작한 다는 것을 알 수 있었습니다. import sys input = sys.stdin.readline N = int(input()) matrix = [list(map(int, input().split())) for _ in range(N)] answer = float('inf') total = 0 for i in range(N): for j in range(N): total += matrix[i][j] for x in range(N - 1): for y in range(1, N - 1): for d1 ..

[백준][Python] 17143 낚시왕

처음에 상어끼리 잡아먹는다는 문장을 못봐서 헤멤. 본 후에는 heap기반 -> 2차원 배열 직접 생성으로 바꿔서 품. import sys input = sys.stdin.readline def move_shark(): new_board = [[0 for _ in range(C)] for _ in range(R)] for x in range(R): for y in range(C): if not board[x][y]: continue t_x, t_y = x, y s, d, z = board[t_x][t_y] total = s if d == 0 or d == 1: s %= 2 * R - 2 while s: if (t_x == R - 1 and d == 1) or (t_x == 0 and d == 0): d ^..