CS/algorithm & data structure

[프로그래머스] [1차] 캐시 (파이썬 풀이)

hjkim0502 2022. 6. 30. 18:48

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

 

코딩테스트 연습 - [1차] 캐시

3 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"] 50 3 ["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul"] 21 2 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "SanFrancisco", "Seoul", "Ro

programmers.co.kr

 

내 풀이:

from collections import deque

def solution(cacheSize, cities):
	# 예외 처리
    if cacheSize == 0:
        return 5 * len(cities)
    
    cache = deque([0] * cacheSize)
    time = 0
    for city in cities:
        city = city.lower()
        # cache hit
        if city in cache:
            time += 1
            cache.remove(city)
            cache.appendleft(city)
        # cache miss
        else:
            time += 5
            cache.pop()
            cache.appendleft(city)

    return time
  • 아이디어: 데크로 캐시 구성해 cities 탐색하면서 캐시에 앞에서부터 최근에 검색한 순서로 배치
  • 예외 처리 더 신경 쓸 것

참고 풀이:

def solution(cacheSize, cities):
    import collections
    cache = collections.deque(maxlen=cacheSize)
    time = 0
    for i in cities:
        s = i.lower()
        if s in cache:
            cache.remove(s)
            cache.append(s)
            time += 1
        else:
            cache.append(s)
            time += 5
    return time
  • 동일한 아이디어지만 데크의 maxlen 기능을 이용해 cache miss 상황에서 pop()할 필요가 없어 더 간결한 코드
  • 여기서는 캐시의 뒤로 갈수록 최근에 검색한 도시이름