○ 알고리즘, 자료구조/2021 알고리즘
코드잇 : 거스름돈 계산기 | 함수, 기본 연산
0ver-grow
2021. 5. 27. 11:10
반응형
주어진 기본 코드
def calculate_change(payment, cost):
# 코드를 작성하세요.
# 테스트
calculate_change(100000, 33000)
print()
calculate_change(500000, 378000)
내가 푼 코드
def calculate_change(payment, cost):
# 코드를 작성하세요.
fifty_thousand = 50000
ten_thousand = 10000
five_thousand = 5000
one_thousand = 1000
rest = payment - cost # 나머지금액
fifty_thousand_rest = rest // fifty_thousand
ten_thousand_rest = (rest % fifty_thousand) // ten_thousand
five_thousand_rest = ((rest % fifty_thousand) % ten_thousand) // five_thousand
one_thousand_rest = (((rest % fifty_thousand) % ten_thousand) % five_thousand) // one_thousand
print("50000원 지폐: {}장".format(fifty_thousand_rest))
print("10000원 지폐: {}장".format(ten_thousand_rest))
print("5000원 지폐: {}장".format(five_thousand_rest))
print("1000원 지폐: {}장".format(one_thousand_rest))
# 테스트
calculate_change(100000, 33000)
print()
calculate_change(500000, 378000)
모범 답안
def calculate_change(payment, cost):
change = payment - cost # 거스름돈 총액
fifty_count = change // 50000 # 50,000원 지폐
ten_count = (change % 50000) // 10000 # 10,000원 지폐
five_count = (change % 10000) // 5000 # 5,000원 지폐
one_count = (change % 5000) // 1000 # 1,000원 지폐
# 답 출력
print("50000원 지폐: {}장".format(fifty_count))
print("10000원 지폐: {}장".format(ten_count))
print("5000원 지폐: {}장".format(five_count))
print("1000원 지폐: {}장".format(one_count))
굳이 누적시킬 필요는 없다.
어차피 10000원권 안에 50000권이 속해있음
반응형