알고리즘

[프로그래머스 Lv2 - 2022 KAKAO BLIND RECRUITMENT] 주차 요금 계산 (Python)

lwkejpf 2022. 9. 16. 02:36

 


 

from collections import defaultdict
import math

def solution(fees, records):
    answer = []
    numbers = []        # 출차 내역 유무 확인
    enter = defaultdict(int)        # {차량번호 : 입차 시간}
    charge = defaultdict(int)       # {차량번호 : 누적된 이용 시간}

    for i in range(len(records)) :
        time, num, io = records[i].split(" ")
        hour, minute = time.split(":")
        total = int(hour)*60 + int(minute)
        if io == 'IN' :
            enter[num] = total 
            numbers.append(num)
        else : 
            total = total - enter[num]
            charge[num] += total
            numbers.remove(num)
            
    # 출차 내역 없을 때 23:59 에 출차되었다고 간주
    for num in numbers :
        total = 23*60+59 - enter[num]
        charge[num] += total

	# 주차 요금 계산
    for car, total in charge.items() :
        if total > fees[0] :
            charge[car] = fees[1] + math.ceil((total - fees[0]) / fees[2]) * fees[3]
        else :
            charge[car] = fees[1]
        
    # 차량 번호 오름차순 정렬 및 answer 반환
    for car, fee in sorted(charge.items()) :
        answer.append(fee)
        
    return answer

 

리스트 numbers 

입차할 때 차량 번호를 append 하고, 출차할 때 remove 

마지막에 numbers 에 남아있는 차량이 있다면 출차 내역이 없다는거니까

23:59 까지 이용한 걸로 간주하고 시간 누적해줌.

 

딕셔너리 enter 

{차량번호 : 입차 시긱} 형태로 집어넣어서

출차 시각에서 enter 에 저장된 입차 시각을 빼서 이용 시간을 계산해줌.

 

딕셔너리 charge

{차량번호 : 총 이용 시간} 형태로,

출차 찍힐 때마다 이용 시간 누적해서 더해줌.

 

 

그리고 마지막에 총 이용 시간으로 주차 요금 계산해주고

차량 번호 오름차순해서 하나씩 answer 에 넣어주면 끝 ..!!!!