데이터사이언스 기록기📚

[프로그래머스/Python] Level 2_주차 요금 계산(2022 KAKAO BLIND RECRUITMENT) 본문

Coding Test/프로그래머스(Python)

[프로그래머스/Python] Level 2_주차 요금 계산(2022 KAKAO BLIND RECRUITMENT)

syunze 2022. 10. 30. 16:50

📌문제 유형

2022 KAKAO BLIND RECRUITMENT

 

📌문제

 

프로그래머스

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

programmers.co.kr

 

📌나의 문제풀이

 - fees의 요소 각각의 변수에 저장

 - 주차 번호대로 정렬

 - {차 번호 : 시간} 저장할 dict 초기화

 - 차랑별 시간 계산(if - elif - else문 설명)

  • i가 리스트의 마지막이고 in_out이 'IN'일 때 : 'OUT'이 없으므로 '23:59'로 설정하고 계산
  • i가 리스트의 마지막이고 in_out이 'OUT'일 때 : 이미 저장되어 있는 in_time과 현재 out_time을 지정하여 계산
  • [i][2]가 'IN'이고 [i+1][2]도 'IN'일 때 : 다음 리스트도 'IN'인 경우, 'OUT'이 없는 것이므로 '23:59'로 설정하여 계산

 - 주차요금 계산

from datetime import datetime
import math

def solution(fees, records):
    answer = []
    time_list = {}
    in_out_check = {}

    basic_time, basic_fee, plus_time, plus_fee = fees
    
    # 주차 번호대로 정렬
    records_sort = [list(map(str,record.split(' '))) for record in records]
    records_sort.sort(key = lambda x:x[1])
    
    # dict 차 번호대로 초기화
    for time, car, in_out in records_sort:
        if car not in time_list.keys():
            time_list[car] = 0
            in_out_check[car] = 0

    # 차량별 시간 계산 후 dict에 저장        
    for i in range(len(records_sort)):
        time, car, in_out = records_sort[i]
        
        if i == len(records_sort) - 1 and records_sort[i][2] == 'IN':
            in_time = time
            out_time = '23:59'
            all_time = str(datetime.strptime(out_time,"%H:%M") - datetime.strptime(in_time,"%H:%M")).split(':')
            time_list[car] += int(all_time[0]) * 60 + int(all_time[1])
        elif i == len(records_sort) - 1 and records_sort[i][2] == 'OUT':
            out_time = time
            all_time = str(datetime.strptime(out_time,"%H:%M") - datetime.strptime(in_time,"%H:%M")).split(':')
            time_list[car] += int(all_time[0]) * 60 + int(all_time[1])
        elif records_sort[i+1][2] == 'IN' and records_sort[i][2] == 'IN':
            in_time = time
            out_time = '23:59'
            all_time = str(datetime.strptime(out_time,"%H:%M") - datetime.strptime(in_time,"%H:%M")).split(':')
            time_list[car] += int(all_time[0]) * 60 + int(all_time[1])
        else:
            if in_out == 'IN':
                in_time = time
            else:
                out_time = time
                all_time = str(datetime.strptime(out_time,"%H:%M") - datetime.strptime(in_time,"%H:%M")).split(':')
                time_list[car] += int(all_time[0]) * 60 + int(all_time[1])
                
    # 주차 요금 계산
    time_list = sorted(time_list.items())       # 주차 번호대로 정렬

    for car_num, time in time_list:
        fee = 0
        time -= basic_time
        if time < 0:
            answer.append(basic_fee)
        else:
            fee += basic_fee
            fee += math.ceil(time/plus_time) * plus_fee
            answer.append(fee)
            
            
    return answer

 

📌다른 사람의 문제풀이

import math

def solution(fees, records):
    check = {}

    for record in records:
        time, number, status = record.split()
        time = time.split(':')
        time = int(time[0])*60 + int(time[1])
        if number not in check:
            check[number] = (0, time, status)
        if status == 'IN':
            check[number] = (check[number][0], time, status)
        elif status == 'OUT':
            total_time, in_time, _ = check[number]
            total_time += time - in_time
            check[number] = (total_time, time, status)

    result = {}

    for number in check.keys():
        total_time, time, status = check[number]
        if status == 'IN':
            total_time += 1439 - time
        fee = fees[1]
        if total_time <= fees[0]:
            result[number] = fee
        else:
            fee = fee + math.ceil((total_time - fees[0]) / fees[2]) * fees[-1]
            result[number] = fee

    return list(map(lambda x : x[1], sorted(result.items())))

 

📌리뷰

- 시간 차이 계산하는 방법 : datetime.steptime()

 

[Python] strftime과 strptime

Python을 사용하여 개발을 하다 보면 날짜를 다뤄야 하는 일이 정말 많다. 항상 검색하여 사용하다 한번 정리해보자!라는 생각으로 글을 써본다. 생각해보니 평소에 제일 많이 사용하는 두 함수가

dev-jy.tistory.com

- 딕셔너리 정렬 : sorted(딕셔너리.items())

- 예외 상황 잘 생각하기

728x90
Comments