[Problem Solving] 주차 요금 계산

Sean·2023년 9월 28일
0

Problem Solving

목록 보기
89/130

문제

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

풀이

아이디어

  • IN, OUT 같은건 따로 신경써주지 않았다. 어차피 시간 순으로 정렬된 것을 준다고 했기 때문에 처음거가 IN이고 나중거가 OUT이기 때문이다.
  • 조심해야 할 건 입차-출차로 끝나는게 아니라 출차하고 나중에 또 입차할 수 있다는 점이다.
  • collections 모듈의 defaultdict(list)를 사용해서 해당 번호에 대한 기록이 나올 때마다 append 해주었다.
  • 위의 defaultdict를 가지고 요금 계산용으로 또 새로운 defaultdict(int)를 생성했다. 이때 입차만 하고 출차 하지 않은 '홀수 개의 기록'에 대해서도 신경을 써 주었다.
  • 차량번호 오름차순으로 각각의 가격을 리스트로 리턴해달라고 했으므로, defaultdict(int).items()를 리스트로 만들어서 정렬한 다음, list comprehension을 이용해서 두 번째 인자(요금)만 추출해낸 리스트를 리턴해주었다.
  • 그리고 여기서 최소 시간 단위는 분이므로, 시간 문자열을 받아서 모두 분으로 바꿔주는 것이 문제를 풀기에 훨씬 훨씬 쉽다.

코드

from collections import defaultdict
import math
def convert2Min(timeStr):
    ret = 0
    hh, mm = timeStr.split(":")
    ret += 60 * int(hh)
    ret += int(mm)
    return ret
    
def solution(fees, records):
    default_time, default_fee, unit_time, unit_fee = fees
    #입차/출차기록 관리
    dictionary = defaultdict(list)
    for record in records:
        time, car_id, rec_type = record.split(" ")
        #분단위로 시간변환
        dictionary[car_id].append(convert2Min(time))
    #총 체류시간을 계산해서 요금으로 변환
    fee_table = defaultdict(int)
    for car, times in dictionary.items():
        total_time = 0
        if len(times) % 2 == 0:
            for i in range(len(times) // 2):
                total_time += times[2*i+1] - times[2*i]
        else:
            for i in range(len(times) // 2):
                total_time += times[2*i+1] - times[2*i]
            total_time += convert2Min("23:59") - times[(len(times) // 2) * 2]
        #요금계산 시작
        if total_time <= default_time:
            fee_table[car] = default_fee
        else:
            fee = math.ceil((total_time - default_time) / unit_time) * unit_fee + default_fee
            fee_table[car] = fee
    #fee_table.items()를 정렬
    temp = sorted(list(fee_table.items()))
    return [x[1] for x in temp]
profile
여러 프로젝트보다 하나라도 제대로, 깔끔하게.

0개의 댓글