몸과 마음이 건전한 SW 개발자

프로그래머스 [Lv. 2] 주차 요금 계산 {언어 : Python} 본문

알고리즘

프로그래머스 [Lv. 2] 주차 요금 계산 {언어 : Python}

스위태니 2024. 4. 27. 02:13

문제 링크

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

 

프로그래머스

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

programmers.co.kr

정답 코드 1 (2023.09.07 코드 - 41 줄)

def solution(fees, records):
    cars = [0 for _ in range(10000)]
    result = [0 for _ in range(10000)]
    for rec in records:
        time, car, io = rec.split()
        car = int(car)
        hh, mm = time.split(":")
        tot = int(hh) * 60 + int(mm)
        tmp = 0
        if io == "IN":
            if tot == 0:
                cars[car] = -1
            else:
                cars[car] = tot     
        else:
            tmp = tot - cars[car]
            result[car] += tmp
            cars[car] = 0
            
    for car in range(10000):
        tmp = cars[car]
        if tmp:
            if tmp == -1:
                result[car] += 1439
            else:
                result[car] += 1439 - tmp
    
    answer = []
    base, baseFee, perM, perFee = fees
    print(base, baseFee, perM, perFee)
    for car in result:
        if car:
            if car > base:
                nowTmp = car - base
                totalFee = baseFee + nowTmp // perM * perFee
                if nowTmp % perM:
                    totalFee += perFee
                answer.append(totalFee)
            else:
                answer.append(baseFee)
    return answer

정답 코드 2 (2024.04.27 코드 - 34 줄)

def solution(fees, records):
    inAndOut = dict()
    for record in records:
        time, number, io = record.split(" ")
        timeArr = time.split(":")
        times = int(timeArr[0]) * 60 + int(timeArr[1])
        if io == "IN":
            if inAndOut.get(number):
                currentTimes = inAndOut[number][2] + inAndOut[number][1] - inAndOut[number][0]
                inAndOut[number] = [times, 24*60-1, currentTimes]
            else:
                inAndOut[number] = [times, 24*60-1, 0]
        else:
            inAndOut[number][1] = times

    answer = []

    normalTimes, normalPrices, perTimes, perPrices = fees

    iaoKeys = sorted(list(inAndOut.keys()))

    for iaoK in iaoKeys:
        startTime, endTime, totalTimes = inAndOut[iaoK]
        totalTimes += (endTime - startTime)
        if normalTimes >= totalTimes:
            answer.append(normalPrices)
        else:
            currentPrices = normalPrices
            totalTimes -= normalTimes
            currentPrices += (totalTimes // perTimes) * perPrices
            if totalTimes % perTimes:
                currentPrices += perPrices
            answer.append(currentPrices)
    return answer

풀이 방법 (2024년)

  1. dictionary를 만든다.
  2. In과 Out을 나눠서 다르게 적용한다.
  3. 총 시간을 측정하고 요금까지 계산한 다음 answer에 넣는다.

느낀점

  • 여러 방법으로 풀 수 있지만 dictionary를 활용하는 것이 코드 가독성도 높고 시간 복잡도도 낮을 것으로 예상되며 권장되는 풀이 방법이다.
  • 전보다 조금 성장한 것 같아서 다행이다.