import math
def dict_sort(records): # 문자열로 주어진 record를 차량번호와 시각으로 분리, 정렬된 사전형으로 변환하는 함수
records_dict = {} # {차량번호 : [시각]}
for record in records:
record = record.split()
if record[1] in records_dict.keys():
records_dict[record[1]].append(record[0])
else :
records_dict[record[1]] = [record[0]]
records_dict = dict(sorted(records_dict.items())) # 차량번호 순으로 정렬
return records_dict
def time_calc(inTime, outTime): # inTime outTime가 '시:분' 형태로 주어져 있을 때 시각 차를 구하는 함수
minute = (int(outTime[0:2]) - int(inTime[0:2])) * 60 + int(outTime[3:]) - int(inTime[3:])
return minute
def solution(fees, records):
records_dict = dict_sort(records)
times = [0] * len(records_dict) # 누적 주차 시간(분)
time_list = list(records_dict.values())
for car in range(len(time_list)):
for i in range(len(time_list[car])):
if i % 2 == 0: # i가 짝수, 즉 입차된 경우
if i + 1 == len(time_list[car]) :
times[car] += time_calc(time_list[car][i], '23:59')
else:
times[car] += time_calc(time_list[car][i], time_list[car][i + 1])
for i in range(len(times)): # 주차 요금 계산
if times[i] < fees[0]:
times[i] = fees[1]
else:
times[i] = fees[1] + math.ceil((times[i] - fees[0]) / fees[2]) * fees[3]
return times
🗝️ 반올림, 올림, 내림
🧩 주어진 자료를 어떻게, 어떤 자료형으로 정리하여야 효율적인지를 고민하는 것이 중요한 것 같다.
🧩 클래스를 활용한 다른 풀이
import math
from collections import defaultdict
class Car: # 차량 번호에 따라 인스턴스를 생성하는 클래스
def __init__(self):
self.times = []
self.total = 0
def carIn(self, inTime): # 입차
self.times.append(inTime)
def carOut(self, outTime): # 출차
inTime = self.times.pop()
self.total += (int(outTime[0:2]) - int(inTime[0:2])) * 60 + int(outTime[3:]) - int(inTime[3:])
def fee(self, fees): # 주차 요금
if self.total < fees[0]:
self.total = fees[1]
else:
self.total = fees[1] + math.ceil((self.total - fees[0]) / fees[2]) * fees[3]
cars = set() # 차량 번호 세트
def solution(fees, records):
parkingFee = defaultdict(lambda : Car()) # Car 클래스의 인스턴스를 저장하는 딕셔너리
for record in records: # 차량별 입/출차 기록
time, car, inout = record.split()
cars.add(car)
if inout == 'IN':
parkingFee[car].carIn(time)
elif inout == 'OUT':
parkingFee[car].carOut(time)
for car in cars:
if len(parkingFee[car].times) == 1: # 출차 기록이 없는 차량 처리
parkingFee[car].carOut('23:59')
parkingFee[car].fee(fees) # 요금 계산
parkingFee[car] = parkingFee[car].total
parkingFee = dict(sorted(parkingFee.items())) # 차량 번호로 정렬
return list(parkingFee.values())