재귀 호출

유준상·2022년 2월 10일
  • 개념

    --> 자기 자신을 다시 호출하는 것

  • 작동

    def openBox():
        print('Open the box.')
        openBox()
    openBox() # Open the box 메시지 출력이 무한 반복

    * 함수를 호출한 곳으로 돌아가는 예약어 --> return 사용

    종이 상자를 10번 여는 재귀 호출 함수

    def openBox():
        global count
        print('Open the box.')
        count -= 1
        if count == 0:
            print('Stop!')
            return
        openBox()
        print('Close the box.')
    count = 10
    openBox()

    --> 재귀 호출을 함수의 복사본이 생겨 호출한다고 생각해보자.
    --> return을 만나면 전 호출로 돌아가서 나머지 부분을 실행한다.

  • 작동 방식의 이해

    1. 숫자 합계 내기

    1) 반복문을 이용한 구현

    sumValue = 0
    for n in range(10, 0, -1):
        sumValue += n
    print(sumValue) # 55

    2) 재귀함수를 이용한 구현

    def addNumber(num):
        if num <= 1:
            return # return을 만나면 전 호출지점 다음을 실행
        return num + addNumber(num-1)
    print(addNumber(10))

    2. 팩토리얼 구하기

    1) 반복문을 이용한 구현

    factValue = 1
    for n in range(10, 0, -1):
        factValue *= n
    print(factValue)

    2) 재귀 함수를 이용한 구현

    def factorial(num):
        if num <= 1:
            return
        return num * factorial(num-1)
    print(factorial(10))
profile
웹사이트 개발과 신발을 좋아하는 학생입니다.

0개의 댓글