알고리즘/프로그래머스문제풀이

[Python/프로그래머스]주차요금계산_[구현]

개발자 덕구🐾 2022. 10. 6. 21:27
728x90

 

 

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

 

프로그래머스

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

programmers.co.kr

 

 

🐾 20221022 - 혼자 품!!

 

 

 

 

코드 : 

def solution(fees, records):
    cost = {}
    dic = {}
    for i in records :
        i  = i.split()
        if i[1] in dic :
            dic[i[1]].append(i[0])
        else :
            dic[i[1]] = [i[0]]
            cost[i[1]] = 0    
    for key, i in dic.items() :
        time = 0
        # in, out이 잘 있을 때 
        if len(i)%2 ==0 :
            for j in range(len(i)) :
                if j %2 !=0 :
                    a = i[j].split(':')
                    b = i[j-1].split(':')
                    a = int(a[0])*60 + int(a[1])
                    b = (int(b[0])*60 + int(b[1]))
                    time += (a-b)
            if time <= fees[0] : cost[key] += fees[1]
            else :
                cost[key] += fees[1]
                time -= fees[0]
                if time %fees[2] >0 :
                    cost[key] += (time//fees[2]+1)*fees[3]
                else :
                    cost[key] += (time//fees[2])*fees[3]
        else :
            for j in range(len(i)-1) :
                if j %2 !=0 :
                    a = i[j].split(':')
                    b = i[j-1].split(':')
                    a = int(a[0])*60 + int(a[1])
                    b = (int(b[0])*60 + int(b[1]))
                    time += (a-b)
            a = i[len(i)-1].split(':')
            time += (1439 - (int(a[0])*60 + int(a[1])))
            if time <= fees[0] : cost[key] += fees[1]
            else :
                cost[key] += fees[1]
                time -= fees[0]
                if time %fees[2] >0 :
                    cost[key] += (time//fees[2]+1)*fees[3]
                else :
                    cost[key] += (time//fees[2])*fees[3]
    cost = sorted(cost.items())
    answer = []
    for i in cost :
        answer.append(i[1])
    return answer

 

어떻게 꾸역꾸역 구현해서 혼자 답을 만들었다..!!👀

아마 코드길이 긴걸로 1등이 아닐까

 

 

 

아니 이게 나는 In, out 별로 다 계산을 했는데

그럴 필요없이 시간을 줄여주면 되는구나 ! 

일단 이거는 다음 기회에

 

 

 

 

 

 

코드를 defaultdict와 math을 이용해서 조금 줄여봤다. 

from collections import defaultdict 
import math 
def solution(fees, records):
    cost = defaultdict(int)
    dic = defaultdict(list)
    answer = []
    for i in records :
        i  = i.split()
        dic[i[1]].append(i[0])
        cost[i[1]] = 0   
    for key, i in dic.items() :
        time = 0
        # in, out이 잘 있을 때
        for j in range(len(i)) :
        	# 출차가 없는 경우 
            if len(i)%2!=0 and j==len(i)-1 :
                a = i[len(i)-1].split(':')
                time += (1439 - (int(a[0])*60 + int(a[1])))
            elif j %2 !=0 :
                a = i[j].split(':')
                b = i[j-1].split(':')
                time += (int(a[0])*60 + int(a[1])) - (int(b[0])*60 + int(b[1])) 
        # 기본요금만 
        if time <= fees[0] : cost[key] += fees[1]
        # 추가요금도
        else :
            cost[key] += fees[1]
            cost[key] += math.ceil((time-fees[0])/fees[2])*fees[3]
    cost = sorted(cost.items())
    for i in cost :
        answer.append(i[1])
    return answer

 

 

1. 

딕셔너리는 정렬할 때 

cost = sorted(cost.items())

 이런 식으로 한다. 

 

 

 

 

2. 올림 

import math 를 한 후에 

' / '로 나누면 소숫점이 나오는데 이 값을 math.ceil로 감싸면된다. 

 

 

 

 

 


 

 

 

복습하면서 나온 코드 : 

from collections import defaultdict 
import math 
def solution(fees, records):
    time = defaultdict(int)
    all_time = defaultdict(int)
    answer = []
    inout = set()
    for r in records :
        r = r.split()
        # out
        if r[1] in inout : 
            inout.remove(r[1])
            hour, minute = r[0].split(':')
            all_time[r[1]] += (int(hour) * 60 + int(minute)) - time[r[1]] 
        # in 
        else : 
            inout.add(r[1])
            hour, minute = r[0].split(':')
            time[r[1]] = int(hour) * 60 + int(minute)
    # out을 안한 차 
    for s in inout:
        all_time[s] += (23 * 60 + 59) - time[s]
    
    # 계산 
    for k,v in all_time.items() :
        cost = fees[1]
        if v > fees[0] :
            cost+= math.ceil((v-fees[0])/fees[2])*fees[3]
        answer.append([int(k),cost])
    answer.sort(key = lambda x : x[0])

    return [i[1] for i in answer ]

이 코드가 더 쉬운것같다.

v-fees[0]에 괄호 하나 더 하는거 잊지말자 

 

set을 만들어서 in이면 넣고 out이면 빼준다.

다 돌고나서 set에 남는다면 그것들은 23:59에 출차한 차로 생각하고 시간을 계산해준다. 

 

시간대로 계산해준다.

만약 기본 시간보다 작거나 같다면 기본 요금으로 answer에 append해주고

크다면 올림을 이용해서 추가 시간으로 나누값을 계산해 추가 요금을 곱해서 cost를 구한다. 

 

차량 번호순으로 sort하고 return 하면 된다. 

 

 

 

 

 

 

 

참고 블로그 : 

 

https://unie2.tistory.com/1094

 

프로그래머스(Python) 92341번 주차 요금 계산 풀이

Python으로 구현한 92341번 주차 요금 계산 문제 풀이입니다. https://programmers.co.kr/learn/courses/30/lessons/92341 코딩테스트 연습 - 주차 요금 계산 [180, 5000, 10, 600] ["05:34 5961 IN", "06:00 000..

unie2.tistory.com

 

 

 

반응형