본문 바로가기
Algorithm/프로그래머스

[프로그래머스] - 캐시 (파이썬)

by 2HS 2022. 1. 30.
from collections import deque

def solution(cacheSize, cities):
    answer = 0
    cache = deque()
    for city in cities:
        city = city.lower()
        if city in cache:
            answer += 1
            for i in range(len(cache)):
                if cache[i] == city:
                    cache.remove(city)
                    break
            cache.append(city)
        else:
            answer += 5
            if cacheSize != 0:
                if cache and len(cache) == cacheSize:
                    cache.popleft()
                cache.append(city)
    return answer

 

2018 카카오 블라인드 1차 - 3번

1. cities의 각 city를 소문자로 변경

2. city가 만약 cache에 있으면

    - answer += 1

    - 해당 캐시를 삭제하고 맨 마지막에 재배치

3. city가 만약 cache에 없으면

    - answer += 5

    - cache의 크기가 꽉 찾다면 popleft하고 city추가

4. return answer