Algorithm/Programmers

[Python] 캐시

느낌표 공장장 2021. 6. 13. 23:57
from collections import deque
def solution(cacheSize, cities):
cache = deque([], maxlen=cacheSize)
time = 0
if cacheSize == 0 :
return len(cities) * 5
for city in cities :
city = city.lower()
if city in cache :
cache.remove(city)
cache.append(city)
time +=1
else :
cache.append(city)
time += 5
return time

풀이

1) 초기 설정 및 cacheSize가 0인경우

from collections import deque
def solution(cacheSize, cities):
cache = deque([], maxlen=cacheSize)
time = 0
if cacheSize == 0 :
return len(cities) * 5

deque 함수maxlen를 설정해주면 그 길이만큼만 deque에 저장할 수 있다. 추가로 값이 더해지면 맨 앞의 값은 삭제된다.

 

cacheSize가 0인경우, 항상 cache miss이므로 전체 길이의 *5를 반환한다.

 

 

2) 도시 이름 배열 처리

for city in cities :
city = city.lower()
if city in cache :
cache.remove(city)
cache.append(city)
time +=1
else :
cache.append(city)
time += 5
return time

1. city가 대문자일 경우도 있고, 소문자일 경우도 있으므로 소문자로 통일해준다.

 

2. 만약 citycache 안에 있다면, cache안에 있는 city는 삭제해주고, 새로 추가해준다. 

    그리고 이 경우는 cache hit 이므로 +1 해준다.

3. citycache 안에 없다면, cache에 추가해주고 cache miss 이므로 +5해준다.

'Algorithm > Programmers' 카테고리의 다른 글

[Python] 압축  (0) 2021.06.15
[Python] 방금 그 곡  (0) 2021.06.14
[Python] 이진 변환 반복하기  (0) 2021.06.13
[Python] 프렌즈4블록  (0) 2021.06.11
[Python] 구명보트  (0) 2021.06.10