728x90
반응형
Today I Learned
선발대에서 배웠던 여러가지 재귀함수들
# 팩토리얼
def factorial(n):
if n<=0: return 1
return n*factorial(n-1)
print(factorial(16)) # 20922789888000
# 피보나치
def fibonacci(a,b,n,count=2):
if count == n: return b
return fibonacci(b,a+b,n,count+1)
print(fibonacci(0,1,12)) # 89
# 파스칼
def pascal(n, a=[1]):
if len(a)==n: return a
return pascal(n, [1]+[a[i-1]+a[i] for i in range(1,len(a))]+[1])
for i in range(1,8):
print(pascal(i))
# [1]
# [1, 1]
# [1, 2, 1]
# [1, 3, 3, 1]
# [1, 4, 6, 4, 1]
# [1, 5, 10, 10, 5, 1]
# [1, 6, 15, 20, 15, 6, 1]
728x90
반응형