- 문제 : https://school.programmers.co.kr/learn/courses/30/lessons/92341
Lv2문제이고, 생각보다 문제가 까다롭다고 생각해서 시간이 오래 걸렸지만 결국 답을 본 문제다!
문제 이해
1. 하루 내에 In에 상응하는 Out이 있는 경우 시간을 계산 한다음 그 시간들을 자동차 번호에 각각 저장한다.(여기서 해시 이용)
dict에 자동차 번호가 있다는 건 입차해 있다는 거고, 이제 출차한다는 의미이므로 자동차 번호의 누적 시간을 계산한다
total[number] += (time(출차 시간) - dic[number](입차 시간))
dict에 자동차 번호가 없으면 입차한다는 의미이므로 dict[number] = time을 해준다
2. 아직 출차를 안 했다는 것은 dict에 number가 있다는 의미이므로 23:59에서 입차 시간을 뺀 시간을 total에 누적한다
3. total에 있는 시간들을 토대로 주차 요금을 계산한다. 초과시간은 올림을 해야하므로 math.ceil()을 이용한다
주차요금이 완료 되었으면 (자동차 번호, 부과된 요금)을 answer에 추가한다
4. 자동차 번호를 오름차순으로 정렬한다
5. answer에서 각 주차요금을 반환한다
- 정답 풀이 :
import math
from collections import defaultdict
def solution(fees, records):
answer = []
dict = {}
total = defaultdict(int)
# 주차한 시간
for record in records :
# 시간, 차량 번호, 상태(In or Out)
time, number, state = record.split()
hour, minutes = time.split(":")
time = int(hour) * 60 + int(minutes)
# 이미 입차되어 있다면
if number in dict :
total[number] += time - dict[number]
del dict[number]
else : # 입차할 경우
dict[number] = time
# 출차를 안 한 경우
max_time = (23 * 60) + 59
for num, t in dict.items():
total[num] += max_time - t
# 요금 계산
basic_minutes, basic_fee, split_minutes, split_fee = fees
for num, t in total.items() :
cost = basic_fee
if t > basic_minutes : # 추가 요금 발생
cost += math.ceil((t - basic_minutes) / split_minutes) * split_fee # 올림 처리
answer.append((num, cost))
# 차량 번호 오름차순
answer.sort()
return [value[1] for value in answer]
- 시도해본 풀이:
from datetime import datetime
def solution(fees, records):
#차 번호, 입차한 시간
dic = {}
#차 번호, 누적 시간
money = {}
for record in records:
a,b,c = record.split(' ')
if c == "IN":
dic[b] = a
if c == "OUT":
#주차한 시간 구하기, 요금계산하기, money에 누적하기
intime = datetime.strptime(dic[b], "%H:%M")
outtime = datetime.strptime(a, "%H:%M")
diff = outtime - intime
time = (diff.seconds) // 60
if b in money:
money[b] += time
else:
money[b] = time
dic[b] = 0
for i in dic:
if dic[i] != 0:
outtime = datetime.strptime("23:59", "%H:%M")
intime = datetime.strptime(dic[i], "%H:%M")
diff = outtime - intime
time = (diff.seconds) // 60
if b in money:
money[i] += time
else:
money[i] = time
for each in money.keys():
if money[each] <= fees[0]:
money[each] = fees[1]
else:
time = money[each]
time -= fees[0]
if time % fees[2] != 0:
time = time // fees[2] + 1
else:
time = time // fees[2]
money[each] = fees[1] + time * fees[3]
answer = []
hello = sorted(money.items(), key = lambda x : x[0])
for a,b in hello:
answer.append(b)
return answer
'코딩테스트 > 기출' 카테고리의 다른 글
[ 2022 KAKAO BLIND RECRUITMENT / 프로그래머스] 92335번 : k진수에서 소수 개수 구하기 (0) | 2022.09.20 |
---|---|
[월간 코드 챌린지 시즌3 / 프로그래머스] 87390번 : n^2 배열 자르기 (0) | 2022.09.18 |
[2018 KAKAO BLIND RECRUITMENT / 프로그래머스] 17677번 : [1차] 뉴스 클러스터링 (0) | 2022.09.18 |
[2019 카카오 개발자 겨울 인턴십/ 프로그래머스] 64065번 : 튜플 (0) | 2022.09.16 |
[/ 프로그래머스] 17680번 : [1차] 캐시 (0) | 2022.09.12 |