본문 바로가기

Coding test

[ 프로그래머스 / 파이썬 ] 이모티콘 할인행사

🔗 Link

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

🧩 Source Code

from itertools import product

def solution(users, emoticons):
    max_subscribers, max_revenue = 0, 0
    n = len(emoticons)
    discount_rate = [10,20,30,40]
    
    for discounts in product(discount_rate, repeat = n):
        subscribers, revenue = 0,0
        for min_discount, max_price in users:
            total_cost = 0
            for emoticon_price, discount_rate in zip(emoticons, discounts):
                if discount_rate >= min_discount:
                    total_cost += emoticon_price / 100 * (100 - discount_rate )
        
            if total_cost >= max_price :
                subscribers += 1
            else : revenue += total_cost
    
        if subscribers > max_subscribers or (subscribers == max_subscribers and max_revenue < revenue) :
            max_subscribers , max_revenue = subscribers  , revenue
    return [max_subscribers , max_revenue]

 

📝 Commentary

할인 정보를 [10,20,30,40]으로 가지고 있고 이를 itertools의 product를 사용해서 구해주었다

from itertools import product

iterable1 = [1, 2]
iterable2 = ['A', 'B']

result = product(iterable1, iterable2)

print(list(result))
# [(1, 'A'), (1, 'B'), (2, 'A'), (2, 'B')]

 

사용방법은 위와 같이 하거나 repeat 인자를 넣어서 조정할 수 있다.

    n = len(emoticons)
    discount_rate = [10,20,30,40]
    
    for discounts in product(discount_rate, repeat = n):

 

이렇게 해주면 할인 정보의 총 조합을 구할 수 있다.

 

그런 다음 이모티콘에 할인율을 적용한 가격을 구해주는데

        for min_discount, max_price in users:
            total_cost = 0
            for emoticon_price, discount_rate in zip(emoticons, discounts):
                if discount_rate >= min_discount:
                    total_cost += emoticon_price / 100 * (100 - discount_rate )

 

이때 사용자가 설정한 가격보다 커야 구매를 한다.

 

가격보다 크면 구독자를 얻게 되고 아니면 그냥 이득이 올라간다.

            if total_cost >= max_price :
                subscribers += 1
            else : revenue += total_cost

 

마지막으로 구독자가 더 많은 경우의 수이거나 혹은 최대 이익이 갱신되는 경우는 바꿔준다.

        if subscribers > max_subscribers or (subscribers == max_subscribers and max_revenue < revenue) :
            max_subscribers , max_revenue = subscribers  , revenue