프로그래밍/Python

프로그래머스_python lv0. 옷가게 할인받기

O'bin 2023. 1. 14. 13:10

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

 

프로그래머스

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

programmers.co.kr

 

 

내 답안 : 

 

1
2
3
4
5
6
7
8
def solution(price):
    if price>=100000:    
        if price>=300000:
            if price>=500000:
                return int(0.8*price) # 구매액 50만 이상일 경우 리턴
            return int(0.9*price) # 구매액 30만 이상일 경우 리턴
        return int(0.95*price) # 구매액 10만 이상일 경우 리턴
    return price    # 구매액 10만 미만일 경우 리턴
cs

 

 

 

개선안 : 

 

1
2
3
4
5
6
7
8
def solution(price):
    if price>=500000:
        price = price *0.8
    elif price>=300000:
        price = price *0.9
    elif price>=100000:
        price = price * 0.95
    return int(price)
cs

 

elif를 이용하면 훨씬 깔끔한 코드가 나온다.

 

 

 

 

1
2
3
4
5
def solution(price):
    discount_rates = {5000000.83000000.91000000.9501}
    for discount_price, discount_rate in discount_rates.items():
        if price >= discount_price:
            return int(price * discount_rate)
cs

 

할인 기준 금액에 따른 할인율을 딕셔너리에 넣어서 처리하는 방법이다.

새로운 방법이기도 하고, 할인 기준이 많아졌을때에는 하나하나 if문으로 만드는 것 보다 이런 방법으로 처리하는것이 효율적일 것이다.