[Pytrhon] 프로그래머스 마법의엘리베이터(divmod(),재귀함수)

민갱·2023년 6월 26일

CT

목록 보기
17/35

마법의 엘리베이터

컨셉은 잡았지만,,, 최초에는 실패😣

실패

# 현재 층수에 누른 버튼의 수를 더한 층으로 이동
# 더한 값이 0보다 작으면 엘리베이터는 움직이지 않음
# 0층이 가장 아래층, (엘리베이터는 현재 민수가 있는 층에 있음)

# 마법돌 최소로 쓰는 방법

def solution(storey):
    answer = 0
    tmp = [i for i in reversed(str(storey))]
    d = {10**i:int(v) for i,v in enumerate(tmp)}

    for i in range(len(d)):
        chk = 0
        if d[10**i] >= 5:
            chk = 10 - d[10**i]
            d[10**(i+1)]=d.get(10**(i+1),0) + 1
        else:
            chk = d[10**i]
        answer += chk

    return answer

# def solution(storey):
#     answer = 0
#     l = len(str(storey))
#     s = str(storey)
    
    
#     if int(s[l-1]) >=5:
#         least = 10 - int(s[l-1])
#         newS = storey + least
#     else:
#         least = int(s[l-1])
#         newS = storey - least
#     answer += least

#     for i in reversed(range(l)):
#         chk = (newS // 10**i)
#         answer += chk
#         newS -= (chk * 10**i)
#     return answer

성공


def solution(storey):
	answer = 0
    if storey <= 0:
    	return storey
    q,s = divmod(storey,10)
    return min(solution(q)+r,solution(q+1)+(10-r))

예를 들어 solution(2554)는 solution(255) + 4 와 solution(256) + 6 둘 중 더 적은쪽이다.
solution(255) + 4은 -1을 4번 하고 2550을 만든 경우고, solution(256) + 6은 +1을 6번하고 2560을 만든 경우이다.

  • storey는 1보다 작거나 같은 경우는 1,0 갯수기 때문에 바로 return 해서 갯수를 반환
  • divmod로 10으로 나눈 몫과 나머지를 구한 이후 재귀함수를 통해서 최초 숫자를 반복해서 나누고 더해나간다,
  • 위에서 말한 가장 작은 자리 숫자가 5보다 작을 경우는 나눈 나머지를 더하고,
    5보다 큰 경우는 10에서 나머지를 뺀 갯수를 더하고 몫에 1을 더해서 구해나간다.

1. divmod()


나누기 연산자
>>> 8 / 2
4.0
>>> 8 // 2
4

나머지 연산자
>>> 8 % 2
0
>>> 8 % 3
2

divmod() 함수
>>> divmod(8, 2)
(4, 0)
>>> (8 // 2, 8 % 2)
(4, 0)

>>> divmod(8, 3)
(2, 2)
>>> (8 // 3, 8 % 3)
(2, 2)
profile
가보자고

0개의 댓글