-
57 - (파이썬) 재귀 함수, 팩토리얼 연산study with Q - 파이썬 2024. 6. 19. 20:03
# 재귀 함수
: 자기 자신을 호출하는 함수
# 팩토리얼 연산
: n! = n * (n-1) * (n-2) ... *1
- 팩토리얼 연산 구현 방법 (1) 반복문을 사용
def fact(n): output = 1 for i in range(1, n+1) : output*= i return output print(fact(2)) print(fact(3)) print(fact(4)) print(fact(5)) print(fact(6)) >>> 2 6 24 120 720
파이썬 튜터로 확인해보면...
더보기def fact(n): output = 1 for i in range(1, n+1) : output*= i return output print(fact(6))
그리고 return value로 호출되고
함수의 스택은 빛났다 사라져 ⭐️
- 팩토리얼 연산 구현 방법 (2) 재귀함수를 사용
# (수학의) 수열의 점화식
: 이웃하는 항들 사이의 관계를 통해 수열을 나타내는 관계식
그러므로 팩토리얼을 점화식으로 나타내면...
1! = 1
(n이 2이상의 자연수일 때) n! = n*(n-1)
def factory(n): if n == 1 : return 1 elif n >= 2 : return n * factory(n-1) print(factory(4)) >>> 24
파이썬 튜터로 확인해보면...
더보기일단 factory라는 함수에 4를 넣고
n = 4가 될 때까지 return을 돌려보면 f(4), f(3), f(2) f(1)을 호출하면서 스택을 만드는 것을 볼 수 있다.
그리고 n=1이 되었으니 f(1), f(2), f(3), f(4)를 리턴하면서 스택을 제거해 나가게 된다.
그리고 리턴값 출력하면 함수도 할일을 다했으니 사라져...ㅁ7ㅁ8
'study with Q - 파이썬' 카테고리의 다른 글
59 - (파이썬) 조기 리턴과 리스트 평탄화하는 재귀 함수 (0) 2024.06.23 58 - (파이썬) 재귀 함수, 피보나치 수, 메모화(memorization) (0) 2024.06.19 56 - (파이썬) 메모리 구조 : 함수의 값 복사와 레퍼런스 복사 (1) 2024.06.15 55 - (파이썬) 메모리 구조: global 키워드 (0) 2024.06.15 54 - (파이썬) 메모리 구조 : 스택과 힙, 함수와 결합할 때 (1) 2024.06.15