Python에서 최대 재귀 횟수는 몇 번이고 어떻게 증가시킬수 있나요??

LONGNEW·2021년 1월 9일
0

StackOverFlaw

목록 보기
13/16

Q. What is the maximum recursion depth in Python, and how to increase it?
Q. Python에서 최대 재귀 횟수는 몇 번이고 어떻게 증가시킬수 있나요??

I have this tail recursive function here:
여기 꼬리 재귀 함수가 존재합니다.

def recursive_function(n, sum):
    if n < 1:
        return sum
    else:
    	# tail_recursion 의 경우 평소에 보던 
        # n * recursive_function(n - 1)
        # 이 아닌 아래와 같은 함수를 쓴다.
        return recursive_function(n-1, sum+n)
        
c = 998
print(recursive_function(c, 0))

It works up to n=997, then it just breaks and spits out a RecursionError: maximum recursion depth exceeded in comparison.
n = 997 일 때 까지는 작동을 하는데, 그걸 넘기는 순간 멈추고 RecursionError: maximum recursion depth exceeded in comparison를 발생시킵니다.
Is this just a stack overflow?
스택 오버 플로우인가요?
Is there a way to get around it?
다른 방법이 있을 까요??


It is a guard against a stack overflow, yes.
스택 오버 플로우를 보호나는 용도입니다.
Python (or rather, the CPython implementation) doesn't optimize tail recursion, and unbridled recursion causes stack overflows.
Puthon이나 CPython의 경우 꼬리 재귀에 최적화 되어 있지 않고, 기저 사례가 존재하지 않은 재귀 함수는 스택 오버플로우를 발생시킵니다.
You can check the recursion limit with sys.getrecursionlimit:
재귀의 한계횟수는 sys.getrecursionlimit로 확인 할 수 있습니다.

import sys
print(sys.getrecursionlimit())

and change the recursion limit with sys.setrecursionlimit:
그리고 한계횟수를 sys.setrecursionlimit으로 지정할 수 있죠.

sys.setrecursionlimit(1500)

but doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.
그러나 표준 한계치가 설정되어 있기에 이를 이용하는 것은 위험합니다. 뭐 그래도 Python에서의 스택의 최대치는 꽤 큽니다.
Python isn't a functional language and tail recursion is not a particularly efficient technique.
Python은 함수형 언어가 아니고, 꼬리 재귀는 특별히 효율적인 기술이 아닙니다.
Rewriting the algorithm iteratively, if possible, is generally a better idea.
가능하다면, 알고리즘을 반복적으로 이용하는 것이 더 좋은 아이디어 입니다.

0개의 댓글