practivceAlgorithm/programmers

[프로그래머스][Python] 2018카카오블라인드1차: 캐시

findTheValue 2021. 9. 2. 00:23

내풀이. deque하면 pop안에 인덱스가 안들어 간다는걸 몰랐다. 그래서 결국 그냥 큐로 바꿈.

def solution(cacheSize, cities):
    cache = []
    total_cost = 0
    for city in cities:
        lo_city = city.lower()
        if lo_city not in cache:
            cache.append(lo_city)
            total_cost += 5
            if len(cache) > cacheSize:
                cache.pop(0)
        else:
            cache.append(cache.pop(cache.index(lo_city)))
            total_cost += 1
    return total_cost

 

남의 코드

볼 것 :maxlen으로 크기제한, remove로 바로 없애기.

# 남의 풀이
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