ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Recursive Function
    Computer Science/Basic Programming with Python 2021. 11. 19. 20:02

    함수내부에서 자기 자신을 부르는 식으로 코딩을 하는 방법이 있는데, 바로 Recursive function이다.

    def function(count):
      if count > 0:
        print(count, 'now')
        function(count - 1)
      print('result:', count)

    위와같이 function안에 function을 불러서 다른 조건으로 처리하는식으로 코딩할 수 있다. 만약 5를 집어넣으면

    function(5)
    
    5 now
    4 now
    3 now
    2 now
    1 now
    result: 0
    result: 1
    result: 2
    result: 3
    result: 4
    result: 5

     

    loop을 쓰는것과 마찬가지로 어떤 동작을 반복적으로 하는것인데, 이러한 recurisve function을 쓸 때 주의할점이 있다. 위의 경우에는 5에서 시작해서 0까지 도달할때까지 깊이가 5인 스택이 쌓이게 되고, 0일때 비로소 다시 하나씩 문제가 풀리게 되는데, 만약 이 깊이가 너무 깊거나, 종료를 하는 condition이 명확하지 않으면 프로그램이 동작하지 않는다.

     

    def no_idea():
      print('I have no idea')
      print('Because I have no idea')
      no_idea()

    위와같이 종료가 없이 자기 자신을 계속 부르는 function을 코딩하게 되면,

    ---------------------------------------------------------------------------
    RecursionError                            Traceback (most recent call last)
    <ipython-input-8-8ff78637fccb> in <module>()
    ----> 1 no_idea()
    
    1 frames
    ... last 1 frames repeated, from the frame below ...
    
    <ipython-input-7-7a6dd964b52e> in no_idea()
          2   print('I have no idea')
          3   print('Because I have no idea')
    ----> 4   no_idea()
    
    RecursionError: maximum recursion depth exceeded while calling a Python object

    위와같이 Recursion Error가 나고, Python 에는 maximum recursion depth 가 있는데, 그것을 넘어가면 더이상 계산을 할 수 없게 된다. 이 recursion depth가 무엇인지는 아래와 같이 확인할 수 있다.

    import sys
    print(sys.getrecursionlimit())
    1000

    몇번의 테스트 결과, 사실 1000이 아닌 function(962)까지는 호출을 할 수 있었고, function(963)부터는 에러를 발생시켰다.

    'Computer Science > Basic Programming with Python' 카테고리의 다른 글

    Lambda  (0) 2021.11.20
    Nested Function  (0) 2021.11.19
    Python Variable  (0) 2021.11.18
    Python Function  (0) 2021.11.14
    Python While  (0) 2021.11.13

    댓글

Designed by Tistory.