알고리즘/프로그래머스

[프로그래머스] 캐시(1) (python)

김홍중 2021. 6. 19. 23:39

문제링크

 

코딩테스트 연습 - [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

 

대문자인 것을 소문자로 안바꿔서 헤맸습니다.

조건을 잘 읽어야 겠습니다.

 

def solution(cache_size, cities):
    answer = 0
    time = 0
    cache = []
    current_cache_size = 0
    index = 0
    isHit = False
    lower_cities = []
    
    if cache_size == 0:
        return len(cities) * 5
    
    for city in cities:
        lower_cities.append(city.lower())
 
    for city in lower_cities:
        for index in range(len(cache)):
            if city == cache[index]:
                if len(cache) == cache_size:
                    del cache[index]
                cache.append(city)
                isHit = True
                time += 1
                break     
                
        if not isHit:
            if len(cache) == cache_size:
                cache.pop(0)
            cache.append(city)
            time += 5
        isHit = False
    
    return time

처음에 짠 코드인데 if문이 많아서 코드 짜면서도 실수가 많아서 시간이 오래걸렸습니다. 뭔가 계속 안풀리고 오래걸리면 다시 문제 조건을 보고 해당 문제를 제대로 이해했는지, 이해한 바를 코드로 잘 옮겼는지, 어떻게 구현할 것인지 다시 한번 차근차근 작성해봐야겠습니다.

이 코드는 보기 힘든 코드라고 판단해서 중복된 코드를 제거하고 보기 편하도록 수정해봤습니다.

 

def cities2lower_cities(cities, lower_cities):
    for city in cities:
        lower_cities.append(city.lower())

def solution(cache_size, cities):
    time = 0
    cache = []
    lower_cities = []
    
    if cache_size == 0:
        return len(cities) * 5
    
    cities2lower_cities(cities, lower_cities)
    
    for city in lower_cities:
        if city in cache:
            cache.remove(city)
            time += 1
        else:
            if len(cache) == cache_size:
                cache.pop(0)
            time += 5
        cache.append(city)
    
    return time
    
print(solution(3, ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"])) # 50
print(solution(3, ["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul"])) #21
print(solution(2, ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "SanFrancisco", "Seoul", "Rome", "Paris", "Jeju", "NewYork", "Rome"])) # 60
print(solution(5, ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "SanFrancisco", "Seoul", "Rome", "Paris", "Jeju", "NewYork", "Rome"])) # 52
print(solution(2, ["Jeju", "Pangyo", "NewYork", "newyork"])) # 16
print(solution(0, ["Jeju", "Pangyo", "Seoul", "NewYork", "LA"])) # 25
print(solution(0, [])) # 0
print(solution(5, ["Jeju", "Jeju", "Jeju"])) # 7
print(solution(5, ["Jeju", "Jeju"])) # 6
print(solution(5, ["Jeju"])) # 5
print(solution(5, [])) # 0
print(solution(5, ["jeju", "Pangyo","jeju", "Pangyo"])) # 12