본문 바로가기
프로그래머스/Lv.2

2022 KAKAO BLIND RECRUITMENT > 주차 요금 계산 - Python, ceil(올림), defaultdict

by 아찌방 2025. 3. 1.

 

 

주소

 

코드 & 풀이

 

from collections import defaultdict
import math

def solution(fees, records):
    in_times = defaultdict(int) # 입고 시간
    total_times = defaultdict(int) # 주차 시간
    last_time = (23 * 60) + 59 # 23:59
    
    def set_time_to_minute(times):
        time, minute = map(int,times.split(":"))
        
        return time * 60 + minute
    
    for record in records:
        time, car_number, order = record.strip().split()
        minute = set_time_to_minute(time)
        
        if order == "IN":
            in_times[car_number] = minute
        else:
            total_times[car_number] += minute - in_times.pop(car_number) # in time에서 삭제
    
    for car_number, in_time in in_times.items(): # 출차 안 된 차들 계산
        total_times[car_number] += last_time - in_times[car_number]
    
    answer = []
    for car_number in sorted(total_times):
        time = total_times[car_number] - fees[0] if total_times[car_number] - fees[0] > 0 else 0
        answer.append(fees[1] + math.ceil(time / fees[2]) * fees[3])
        
    return answer

 

 

그냥 빡 구현했음 ⇒ 더 좋은 방법 있으면 추천해주세요.

 

1. 준비

 

들어온 타임을 저장하는 딕셔너리, 출차 후 주차된 시간을 저장하는 딕셔너리 두개로 나눔.

⇒ 이해하기 쉬우니까

 

그리고 입고 후 출차를 안 한 경우 23:59에 출차한걸로 본다는 개꿀 주차장임.

그래서 last_time을 (23 * 60) + 59 로 선언해줬음 ⇒ 왜 1439로 안 하냐? ⇒ 남들이 보면 저게 무슨 값인지 알 수 없음.

 

2. 주어진 시간을 분 단위로 변경

→ 분이 넘어가면 시간 올리는 거 관리하기 귀찮으니까

 

3. 입출고 관리

 

그 후 records를 돌면서

 

in 이면 in_times에 저장

 

out이면 현재 시간에서 in_time[car_number] 값을 빼서 total_time에 주차 시간 저장

 

4. 출고 안 한 차 계산

그리고 입고 후 출차 안 한 차들이 있으면 last_time을 기준으로 계산 후 total_time에 저장

 

5. 주차비 계산

그리고 마지막으로 total_time을 sorted 하면 key값이 정렬된 리스트가 주어지니까

 

이걸로 주차요금을 계산하면서 answer에 저장해가면 완성

 

계산 할 때 주의할 점은 기본 시간을 제외한 나머지 시간 / 기준 시간 을 올림 처리 해줘야 한다는 것임.

 

⇒ math.ceil 사용했음.

다른 방법 있으면 알려주세요.

 

처음에 출차한 차량을 삭제하려고 del을 썼는데

 

defaultdict.pop(key)를 사용하면 더 깔끔하게 사용할 수 있다는 것을 알게 되서 수정함.

 

 

 

 

다음에 또 봐요

 

728x90