Practice 3 : 함수 2

불쌍한 달팽이

달팽이는 낮 시간 동안에 기둥을 올라간다. 하지만 밤에는 잠을 자면서 어느 정도의 거리만큼 미끄러진다. (낮 시간 동안 올라간 거리보다는 적게 미끄러진다.)

달팽이가 기둥의 꼭대기에 도달하는 날까지 걸리는 시간을 반환하는 함수 snail()을 작성하시오.

함수의 인자는 다음과 같다.

  1. 기둥의 높이(미터)

  2. 낮 시간 동안 달팽이가 올라가는 거리(미터)

  3. 달팽이가 야간에 잠을 자는 동안 미끄러지는 거리(미터)


예시)

snail(100, 5, 2) #=> 33
def snail(height, day, night):
    times = 1
    while height >= day:
        height -= (day - night)
        times += 1
    return times
def snail(height, day, night):
    count = 0
    total = 1
    while True:
        count += 1
        total += day
        if total >= height:
            return count
        total -= night
def snail(height, day, night):
    count = 0
    while True:
        count += 1
        height -= day
        if height <= 0:
            return count
        height += night
# 해당 코드를 통해 올바른 결과가 나오는지 확인하시오.
print(snail(100, 5, 2))
33

자릿수 더하기 (SWEA #2058)

자연수 number를 입력 받아, 각 자릿수의 합을 계산하여 출력하시오.


예시)

sum_of_digit(1234) #=> 10
sum_of_digit(4321) #=> 10
def sum_of_digit(number):
    total = 0
    while number > 0:
        total += number % 10
        number = number//10
    return total
def sum_of_digit(number):
    if number < 10:
        return number
    return number % 10 + sum_of_digit(number // 10)
def sum_of_digit(number):
    if number < 10:
        return number
    quotient, remainder = divmod(number, 10)
    return sum_of_digit(quotient) + remainder
def sum_of_digit(number):
    chars = list(str(number))
    total = 0
    return sum(map(int, chars))
# 해당 코드를 통해 올바른 결과가 나오는지 확인하시오.
print(sum_of_digit(1234))
print(sum_of_digit(4321))
10
10