동캄의 코딩도장

프로그래머스 level2 [1차 캐시] 파이썬 본문

코테/프로그래머스

프로그래머스 level2 [1차 캐시] 파이썬

동 캄 2021. 12. 8. 13:19

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

#프로그래머스 [1차] 캐시

def solution(cacheSize, cities):
    answer = 0
    for i in range(len(cities)):
        cities[i]=cities[i].upper()
    lst=[]
    for i in range(len(cities)):
        if cities[i] in lst:
            ind=lst.index(cities[i])
            lst.append(lst.pop(ind))
            answer+=1
        else:
            lst.append(cities[i])
            if len(lst)>cacheSize:
                lst.pop(0)
            answer+=5
    return answer

캐시를 lst에 담는다. city가 lst(캐시)에 존재하면, 캐시의 맨끝으로 city를 옮긴다.

존재하지 않으면, 캐시에 삽입한다.