[Python] recursive call : Fibonacci Sequence

2023. 5. 24. 16:14·Programming
728x90
728x90

Recursive call의 경우, 특정 함수가 내부에서 자기자신을 다시 호출하는 것을 가르킴.

다음과 같은 재귀적인 수식을 있는 그대로 작성하게 해준다는 장점은 있지만,

속도 및 메모리 사용 등의 측면에서는 그리 환영받지는 못함 (때문에 많이 사용되지 않음).

$$
f(t) = f(t-1) + ...
$$

$f(t)$를 정의하는데에 같은 함수가 사용되는 경우를 recursive call로 작성하면 매우 직관적인 구현이 가능하다.

대표적인 예로 Fibonacci sequence를 들 수 있다.

$$
f(0) = 0, \\
f(1) = f(2) = 1 \\
f(n) = f(n-1) + f(n-2) \text{ , where }n >2
$$


Python 구현 : Recursive call 이용한 경우.

def fibonacci_recur(num):
  ret = -1
  if num <0:
    print('ERROR: negative is not supported')
  elif num <=1 :
    ret = num
  elif num == 2: 
    ret = 1      
  else: 
    ret = fibonacci_recur(num-1) + fibonacci_recur(num-2) 
  return ret 


for i in range(0,10,1):
  # print(i)
  print(fibonacci_recur(i), end=",")
print('\n')

Python 구현 : while 문을 이용한 경우.

def fibonacci_loop(num):
  if num == 0 or num == 1:    
    return num
  elif num == 2:
    return 1
  else:
    length = num - 2

    first = 1
    second = 1    

    while length > 0:
      tmp = second
      second = first + second
      first = tmp

      length -=1    
    return second

for i in range(1,10,1):
  # print(i)
  print(fibonacci_loop(i), end=",")
print('\n')

사실 while문을 이용한 경우, fibonacci_loop함수 내에서 수열을 출력하도록 수정하면 훨씬 효과적으로 피보나치 수열을 출력할 수 있다. (위의 경우, fibonacci_loop에서는 수열을 출력하기 보다 최종값만을 구하는 형태임).

 

즉, while문을 이용하여 fibonacci_print함수를 만들고 호출시 argument로 수열을 출력해줄지 최종 값만 반환할지를 선택케 하는 형태로 만들면 효과적이다. 이 구현은 간단하니 한번 만들어 보길...

'Programming' 카테고리의 다른 글

[Programming] Garbage Collection (GC)  (0) 2023.06.05
[Python] Interpreter and PVM (Python Virtual Machine)  (1) 2023.06.05
[ML] Levenshtein distance  (1) 2023.05.17
[Python] argparse 사용하기.  (0) 2023.04.05
[NumPy] searchsorted  (0) 2023.03.29
'Programming' 카테고리의 다른 글
  • [Programming] Garbage Collection (GC)
  • [Python] Interpreter and PVM (Python Virtual Machine)
  • [ML] Levenshtein distance
  • [Python] argparse 사용하기.
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (740)
      • Private Life (13)
      • Programming (186)
        • DIP (104)
        • ML (26)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (351)
        • Signals and Systems (103)
        • Math (172)
        • Linear Algebra (33)
        • Physics (42)
        • 인성세미나 (1)
      • 정리필요. (54)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (1)
        • PET Study 2009 (1)
        • 방사선 장해방호 (4)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    Probability
    random
    numpy
    opencv
    검사
    Programming
    function
    Optimization
    인허가제도
    SS
    signals_and_systems
    math
    Convolution
    fourier transform
    SIGNAL
    Python
    Vector
    Term
    signal_and_system
    linear algebra
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[Python] recursive call : Fibonacci Sequence
상단으로

티스토리툴바