[Programmers] Level 2. 캐시

Seo Seung Woo·2022년 9월 16일
0
post-thumbnail

Level 2. 캐시


❔Thinking

  • 크기가 정해진 cache에 값을 저장하고, 검색 비용(시간)을 계산하여 출력한다.
  • cache에 있을 경우 1, 없는 경우 5를 검색 비용(시간)으로 한다.
  • 총 검색 비용(시간)을 계산하여 출력한다.

💻Solution

from collections import deque
def solution(cacheSize, cities):
    if cacheSize == 0:
        return len(cities) * 5
    delay = 0
    cache = deque()
    for city in cities:
        # LRU 알고리즘
        if city.lower() in cache:
            delay += 1
            cache.remove(city.lower())
            cache.append(city.lower())
        else:
            delay += 5
            if len(cache) >= cacheSize:
                cache.popleft()
            cache.append(city.lower())

    return delay

🗝️keypoint

  • deque()에 maxlen을 적용하면, maxlen이 넘을 경우 자동으로 pop이 되어 length가 유지된다.

    q = deque(maxlen=3)

profile
Code for people

0개의 댓글