


주어진 records에서 순서대로 입출차 시간을 계산하면서 전체 주차 시간을 구하고 최종 시간을 기준으로 주차요금을 계산하면 된다.
이때 파이썬의 datetime 라이브러리를 통해 시간계산을 매우 쉽게 할 수 있다. 그리고 dict에서 차량 번호를 key로 주차 시간을 저장한다.
parking_lot dict에 records를 순회하면서 'IN'이면 차량 번호와 입차 시간을 추가하고 'OUT'이면 출차 시간와 입차 시간을 통해 주차한 시간을 계산한다. datetime의 timedelta를 사용했다. 그리고 result에 해당 주차 시간을 더한다. 같은 차량이 여러번 입차할 수 있기 때문에 defaultdict를 통해 주차 시간을 value에 더해준다.
그리고 만약 순회가 끝났는데 parkig_lot에 차가 남아있다면 출차시간을 '23:59'로 상정하여 주차 시간을 계산한다.
위에서 구한 주차 시간 dict인 result와 주어진 fees를 통해 주차 요금을 계산한다.
이때 차량 번호를 기준으로 정렬하여 answer에 차량번호가 작은 순으로 들어갈 수 있도록 한다.
from datetime import datetime
from datetime import timedelta
from collections import defaultdict
import math
SECONDS_PER_MINUTES = 60
def solution(fees, records):
answer = []
parking_lot = dict()
result = defaultdict(int)
for record in records:
time, num, status = record.split()
time = datetime.strptime(time, "%H:%M")
if status == "IN":
parking_lot[num] = time
else:
total_time = (time - parking_lot[num]).total_seconds() / SECONDS_PER_MINUTES
result[num] += total_time
parking_lot.pop(num)
if parking_lot:
for num, time in parking_lot.items():
total_time = (datetime.strptime("23:59", "%H:%M") - time).total_seconds() / 60
result[num] += total_time
result = sorted(result.items(), key=lambda x : x[0])
for num, charged in result:
if charged <= fees[0]:
answer.append(fees[1])
else:
fee = fees[1] + math.ceil((charged - fees[0]) / fees[2]) * fees[3]
answer.append(fee)
return answer