코딩도장
[파이썬 코딩 도장] Unit 31. 함수에서 재귀호출 사용하기
박뮤트
2021. 12. 30. 23:37
재귀호출 recursive call: 함수 안에서 함수 자기 자신을 호출하는 것
def hello():
print('Hello, world!')
hello()
hello()
Hello, world!
Hello, world!
Hello, world!
...(생략)
Traceback (most recent call last):
File "C:\project\recursive_function_error.py", line 5, in <module>
hello()
File "C:\project\recursive_function_error.py", line 3, in hello
hello()
File "C:\project\recursive_function_error.py", line 3, in hello
hello()
File "C:\project\recursive_function_error.py", line 3, in hello
hello()
[Previous line repeated 974 more times]
File "C:\project\recursive_function_error.py", line 2, in hello
print('Hello, world!')
RecursionError: maximum recursion depth exceeded while pickling an object

* 최대 재귀 깊이는 1000이기 때문에 재귀 함수의 종료 조건을 만들어 줘야 한다.

재귀호출을 사용해 팩토리얼 구현하기
* 팩토리얼: 1부터 n까지의 양의 정수를 차례대로 곱한 것
def factorial(n):
if n == 1: # n이 1일 때
return 1 # 1을 반환하고 재귀호출을 끝냄
return n * factorial(n - 1) # n과 factorial 함수에 n - 1을 넣어서 반환된 값을 곱함
print(factorial(5))