본문 바로가기

⏳ 알고리즘/python 알고리즘 문제 풀이

프로그래머스 - LV2. 주차 요금 계산

문제 

https://school.programmers.co.kr/learn/courses/30/lessons/92341

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

코드

defaultdict, 딕셔너리 정렬, math.ceil이용

from collections import defaultdict
import math
def solution(fees, records):
    answer = []
    
    # records_split : records를 차 번호 순대로 정렬 
    records_split = []
    for r in records:
        records_split.append(r.split(' '))
    records_split.sort(key = lambda x : x[1])
    
    # cars 딕셔너리 : cars[차 번호] = 주차한 총 시간 
    cars = defaultdict(int)
    for r in records_split:
        if r[1] not in cars.keys():
            cars[r[1]] = 0
    
    # 차별로 주차한 총 시간 계산
    while records_split:
        if records_split[0][2] == 'IN':
            car_in = records_split.pop(0)
            car_num = car_in[1]
            car_in_time = list(map(int, car_in[0].split(':')))
        if not records_split or car_num != records_split[0][1]:
            car_out_time = [23,59]
        else:
            car_out = records_split.pop(0)
            car_out_time = list(map(int, car_out[0].split(':')))
        hour = car_out_time[0]-car_in_time[0]
        minutes = car_out_time[1]-car_in_time[1]
        cars[car_num] += hour*60 + minutes
    
    # 차 번호를 오르차순으로 정렬하고, 요금 계산
    sorted_cars = dict(sorted(cars.items()))
    for c in sorted_cars:
        if sorted_cars[c] <= fees[0]:
            answer.append(fees[1])
        else:
            answer.append(fees[1]+int(math.ceil((sorted_cars[c]-fees[0])/fees[2]))*fees[3])
    
    return answer