캐시 저장 : 스택, 큐

solee·2022년 9월 19일
0

Python

목록 보기
16/16

https://school.programmers.co.kr/learn/courses/30/lessons/17680

LRU! 일단 각이 나와서 한번 짜 보면 이렇게 나온다.

def solution(cacheSize, cities):
    answer = 0
    memory = []
    
    if cacheSize == 0:
        return len(cities) * 5
    
    for city in cities:
        city = city.upper()
        if city not in memory:
            if len(memory) == cacheSize:
                memory = memory[1:]
            memory.append(city)
            answer += 5
        else:
            memory.remove(city)
            memory.append(city)
            answer += 1
    return answer

memory에 city가 들어 있을 때 remove, append 해줌으로써 캐시 업데이트를 해 주고, 없을 경우는 cache miss이므로 길이를 확인한 후 슬라이싱해서 캐시 길이를 cacheSize로 유지한다.



다만 생각하지 못했던 것은:

import collections
cache = collections.deque(maxlen=cacheSize)

collections! maxlen을 지정해주는 것으로 저런 귀찮은 부분을 다 넘겨버린다.
우와우.....

profile
DA DA DA

0개의 댓글