Python

재귀호출

haventmetyou 2023. 10. 17. 09:49
재귀호출 사용
>>> def hello():
...     print('hello, world')
...     hello()
...
>>> hello()

# 실행 결과
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
hello, world
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in hello
  File "<stdin>", line 3, in hello
  File "<stdin>", line 3, in hello
  [Previous line repeated 993 more times]
  File "<stdin>", line 2, in hello
RecursionError: maximum recursion depth exceeded while calling a Python object
hello, world

 

RecursionError: maximum recursion depth exceeded while calling a Python object

재귀호출이 종료되지 않으면 최대 재귀 깊이를 초과해 에러 발생

 

재귀호출에 종료 조건 만들기

# 함수 정의
def hello(count):
    if count == 0:
        return
    
    print('hello, world', count)

    count -= 1
    hello(count)
    
# 함수 호출
hello(5)

# 실행 결과
hello, world 5
hello, world 4
hello, world 3
hello, world 2
hello, world 1

 

재귀호출로 팩토리얼 구하기
def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n-1)

print(factorial(5))

# 실행 결과
120

함수를 변수 또는 리스트에 넣어 호출 O

def hello():
    print('hello')

x = hello    # 함수를 변수에 할당
x()          # 함수 호출

y = [hello, hello]
y[0]()
y[1]()

# 실행 결과
hello
hello
hello

순수 함수와 비순수 함수

# 비순수 함수(수정자 함수)
# 함수의 실행이 외부 상태에 영향을 줌
number_list = [1, 2, 3]

def append_number(n):
    number_list.append(n)

append_number(5)
print(number_list)

# 실행 결과
[1, 2, 3, 5]

# 순수 함수
# 외부 상태에 영향 x, 부수 효과가 없어야 하고 입력 값이 같으면 언제나 같은 출력 값
def add(a, b):
    return a + b

print(add(1, 2))

# 실행 결과
3