피보나치 수열은 다음과 같은 정수열의 숫자입니다. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ….. 수학적으로 피보나치 수열의 수열 Fn은 반복 관계로 정의됩니다.
에프 N = Fn-1+ 에프n-2
시드 값 포함: 에프 0 = 0 및 에프 1 = 1.
기본 접근 방식을 사용한 피보나치 수
피보나치 수열을 이용한 Python while 루프 구현됩니다.
파이썬3
n>=> 10> num1>=> 0> num2>=> 1> next_number>=> num2> count>=> 1> while> count <>=> n:> >print>(next_number, end>=>' '>)> >count>+>=> 1> >num1, num2>=> num2, next_number> >next_number>=> num1>+> num2> print>()> |
>
>
산출
1 2 3 5 8 13 21 34 55 89>
재귀를 사용하는 피보나치 수에 대한 Python 프로그램
파이썬 다음을 사용하여 n번째 피보나치 수를 찾는 함수 파이썬 재귀 .
파이썬3
def> Fibonacci(n):> ># Check if input is 0 then it will> ># print incorrect input> >if> n <>0>:> >print>(>'Incorrect input'>)> ># Check if n is 0> ># then it will return 0> >elif> n>=>=> 0>:> >return> 0> ># Check if n is 1,2> ># it will return 1> >elif> n>=>=> 1> or> n>=>=> 2>:> >return> 1> >else>:> >return> Fibonacci(n>->1>)>+> Fibonacci(n>->2>)> # Driver Program> print>(Fibonacci(>9>))> |
>
>산출
34>
시간 복잡도: O(2 ^ n) 지수
보조 공간: 에)
DP(동적 프로그래밍)를 사용한 피보나치 수열
Python 동적 프로그래밍 첫 번째 두 개의 피보나치 수를 0과 1로 취합니다.
파이썬3
# Function for nth fibonacci> # number> FibArray>=> [>0>,>1>]> def> fibonacci(n):> > ># Check is n is less> ># than 0> >if> n <>0>:> >print>(>'Incorrect input'>)> > ># Check is n is less> ># than len(FibArray)> >elif> n <>len>(FibArray):> >return> FibArray[n]> >else>:> >FibArray.append(fibonacci(n>-> 1>)>+> fibonacci(n>-> 2>))> >return> FibArray[n]> # Driver Program> print>(fibonacci(>9>))> |
>
>산출
34>
시간 복잡도: 에)
보조 공간: 에)
피보나치 수열 최적화
여기에서도 공간 최적화 첫 번째 두 개의 피보나치 수를 0과 1로 취합니다.
파이썬3
# Function for nth fibonacci number> def> fibonacci(n):> >a>=> 0> >b>=> 1> > ># Check is n is less> ># than 0> >if> n <>0>:> >print>(>'Incorrect input'>)> > ># Check is n is equal> ># to 0> >elif> n>=>=> 0>:> >return> 0> > ># Check if n is equal to 1> >elif> n>=>=> 1>:> >return> b> >else>:> >for> i>in> range>(>1>, n):> >c>=> a>+> b> >a>=> b> >b>=> c> >return> b> # Driver Program> print>(fibonacci(>9>))> |
>
>산출
34>
시간 복잡도: 에)
보조 공간: 오(1)
캐시를 사용한 피보나치 수열
lru_cache 동일한 숫자에 대해 피보나치를 다시 찾을 필요가 없도록 결과를 저장합니다.
파이썬3
from> functools>import> lru_cache> # Function for nth Fibonacci number> @lru_cache>(>None>)> def> fibonacci(num:>int>)>->>>int>:> ># check if num is less than 0> ># it will return none> >if> num <>0>:> >print>(>'Incorrect input'>)> >return> ># check if num between 1, 0> ># it will return num> >elif> num <>2>:> >return> num> ># return the fibonacci of num - 1 & num - 2> >return> fibonacci(num>-> 1>)>+> fibonacci(num>-> 2>)> # Driver Program> print>(fibonacci(>9>))> |
>
>산출
34>
시간 복잡도: 에)
보조 공간: 에)
역추적을 사용한 피보나치 수열
다음을 사용하여 n번째 피보나치 수에 대한 함수파이썬3
라제쉬 칸나
def> fibonacci(n, memo>=>{}):> >if> n <>=> 0>:> >return> 0> >elif> n>=>=> 1>:> >return> 1> >elif> n>in> memo:> >return> memo[n]> >else>:> >memo[n]>=> fibonacci(n>->1>)>+> fibonacci(n>->2>)> >return> memo[n]> # Driver Program> print>(fibonacci(>9>))> |
>
>산출
34>
시간 복잡도: 에)
보조 공간: 에)
전체 기사를 참조하세요. 피보나치 수 프로그램 상세 사항은!