알고리즘/Python

[python] 프로그래머스 - 주차 요금 계산

제주도랏맨 2022. 3. 1. 03:38

출처 : 프로그래머스 코딩테스트 연습, https://programmers.co.kr/learn/courses/30/lessons/92341

 

코딩테스트 연습 - 주차 요금 계산

[180, 5000, 10, 600] ["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"] [14600, 34400, 5000]

programmers.co.kr

 

더보기

풀이

 

import math

def time_calculate(time_in, time_out):
    if time_out[1] < time_in[1]:
        time_out[0] -= 1
        time_out[1] += 60
        
    return (time_out[0] - time_in[0]) * 60 + time_out[1] - time_in[1]

def price_calculate(fees, parking_time):
    basic_time, basic_price, unit_time, unit_price = fees
    
    if parking_time <= basic_time:
        return basic_price
    else:
        return basic_price + math.ceil((parking_time - basic_time) / unit_time) * unit_price
    
def solution(fees, records):
    parking = {}
    total = {}
    
    for record in records:
        time, car, inout = record.split()
        time = list(map(int, time.split(':')))
        
        if car not in parking:
            parking[car] = time
        else:
            time_in = parking.pop(car)
            
            if car not in total:
                total[car] = time_calculate(time_in, time)
            else:
                total[car] += time_calculate(time_in, time)
            
    for car in parking:
        if car not in total:
            total[car] = time_calculate(parking[car], [23, 59])
        else:
            total[car] += time_calculate(parking[car], [23, 59])
            
    answer = []
    
    total = sorted(total.items())
    
    for car, parking_time in total:
        answer.append(price_calculate(fees, parking_time))
    
    return answer

 

solution

parking은 in/out을 구분하기 위한 dict, total을 차별 누적 시간을 구하기 위한 dict

 

1. record에서 시, 분, 차번호, inout을 모두 분리한다.

2. parking에 차번호가 없다면 in이므로 parking[차번호] = [시, 분]으로 넣는다.

3. parking에 차번호가 있다면 out이므로 parking[차번호]를 pop해서

   in시간과 out시간 사이의 분을 계산해 total에 누적합산한다.

4. for을 다 돌고 parking에 차가 남아있다면 안나온 차들이므로 23:59로 계산하여 total에 누적합산한다.

5. total에서 차번호를 기준으로 정렬한다.

6. total의 주차 누적 시간을 가져와 요금을 계산하여 answer에 추가한다.

 

time_calculate

1. time_in과 time_out을 받아 time_in의 분이 time_out의 분보다 크다면 시간에서 1을 빼고 time_out에 60분 추가

2. 시간 계산 후 return

 

price_calculate

1. fees와 parking_time(분)을 받아 기본 시간보다 같거나 적다면 기본요금 return

2. 아니라면 계산 후 return

 


 

시간 복잡도

 

-

 

다른 사람의 풀이를 보면서 알게 된 점

 

-

 

고찰

 

실제로 카카오 코테 때 풀어봤는데 시간 계산이나 요금 계산을 한번에 다 하려고 해서 코드가 더러웠는데

지금은 다 분리해서 그런지 코드 짜기도 편했고, 코드도 깔끔해진 것 같다.