문제
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 풀이
단순 구현 문제이다. 시키는 대로 따라가면 해결되는 문제.
하지만 cacheSize가 0인 특이 케이스를 생각하지 못하면 헤맬 수 있다.
코드
def solution(cacheSize, cities):
answer = 0
cache_hit = 1
cache_miss = 5
cache = dict()
if cacheSize == 0:
return len(cities) * 5
for index,i in enumerate(cities):
i = i.lower()
if len(cache) < cacheSize :
if i not in cache:
answer += 5
else:
answer += 1
cache[i] = index
else:
if i in cache.keys():
answer += 1
cache[i] = index
else:
LRU = min(cache.items(),key= lambda item : item[1])
del cache[LRU[0]]
answer += 5
cache[i] = index
return answer
print(solution(3,["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "SanFrancisco", "Seoul", "Rome", "Paris", "Jeju", "NewYork", "Rome"]))
후기
큐를 사용했다면 더 깔끔한 코드가 나왔을 것 같다.
'알고리즘 > 프로그래머스' 카테고리의 다른 글
프린터 (Python) (0) | 2023.01.17 |
---|---|
n^2배열 자르기 (Python) (0) | 2023.01.17 |
H-Index (Python) (0) | 2023.01.16 |
멀리 뛰기 (Python) (0) | 2023.01.16 |
점프와 순간이동 (Python) (0) | 2023.01.16 |