02

Aug# Fibonacci Series in Python

## Fibonacci Sequence

The Fibonacci sequence is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1. The numbers in the Fibonacci sequence are known as Fibonacci numbers.

In this **Python tutorial**, we'll learn various methods to calculate the nth term and print the Fibonacci series in Python.

Read More: Top 50 Python Interview Questions and Answers |

## Fibonacci Sequence Formula

The Fibonacci formula is used to find the nth term of the sequence when its first and second terms are given. The nth term of the Fibonacci Sequence is represented as Fn. We can calculate the nth term of the Fibonacci series using the following recursive formula,

```
Fn = Fn-1 + Fn-2
```

where,

- n > 1
- The first term is 0 i.e., F0 = 0
- The second term is 1 i.e., F1 = 1

## Calculation of the nth term of the Fibonacci Series in Python

### 1. Using a while loop

```
nterms = 8
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
```

In the above code, the variable "nterms" stores the number of terms. We initialize the first term to 0 and the second term to 1. If nterms is greater than 2, we use a **while loop in Python** to find the next term in the sequence by adding the preceding two terms. Afterward, we interchange the variables and the process continues.

#### Output

```
Fibonacci sequence:
0
1
1
2
3
5
8
13
```

### 2. Using for Loop

```
num = 8
n1, n2 = 0, 1
print("Fibonacci Series:")
print(n1)
print(n2)
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3)
print()
```

#### Output

```
Fibonacci Series:
0
1
1
2
3
5
8
13
```

Read More: Python For Loop |

### 3. Using Recursion

```
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 8
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
```

The above code uses a recursive function recur_fibo() to calculate the nth term of the sequence. We use a for loop to iterate and calculate each term recursively.

#### Output

```
Fibonacci sequence:
0
1
1
2
3
5
8
13
```

Read More: Recursion in Data Structures |

### 4. Using Dynamic Programming

In this technique, we store already computed terms in a lookup table. Before adding any term, we check if it exists in the lookup table. This avoids recomputing the words and makes the algorithm faster.

```
def fibonacci(n):
# Initialize a list to store Fibonacci numbers up to n
fib_cache = [0, 1] + [None] * (n - 1)
# Iterate through the list, calculating Fibonacci numbers on demand
for i in range(2, n + 1):
if fib_cache[i] is None:
fib_cache[i] = fib_cache[i-1] + fib_cache[i-2]
return fib_cache[n]
for i in range(10):
print(fibonacci(i), end=" ")
```

We initialize a dictionary memo to store the Fibonacci numbers. The function first checks if the term already exists in a memo before computing it.

#### Output

```
0 1 1 2 3 5 8 13 21 34
```

### 5. Using Caching

The Python lru_cache decorator can cache and reuse previously computed Fibonacci terms.

```
from functools import lru_cache
@lru_cache(maxsize=1000)
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
def main():
print("Fibonacci series:")
for i in range(8): # Adjust the range according to your desired number of terms
print(fib(i), end=" ")
if __name__ == "__main__":
main()
```

The above program defines the fib function to recursively generate the Fibonacci series up to the nth term using memoization with the @lru_cache decorator.

#### Output

```
Fibonacci series:
0 1 1 2 3 5 8 13
```

### 6. Using Backtracking

Backtracking is not an efficient approach for generating the Fibonacci Series because it involves exploring all possible paths in the search space. It can lead to unnecessary computations exploring irrelevant paths.

## Practical Examples and Use Cases of the Fibonacci Series in Python

**Algorithm Optimization:**The Fibonacci series helps in teaching recursion and dynamic programming techniques.**Mathematical Modeling:**Fibonacci numbers often appear in mathematical modeling and analysis, such as in the study of population growth, the golden ratio, etc.**Numerical Analysis:**Fibonacci numbers are used in numerical analysis for approximating solutions to various mathematical problems, including optimization and root finding.**Computer Graphics:**Fibonacci sequences are employed in computer graphics and visual effects to generate patterns, textures, and animations.**Algorithm Design:**Fibonacci numbers can be used as inputs or constraints in the design and analysis of algorithms, such as in sorting, searching, and graph traversal algorithms.**Data Compression:**Fibonacci codes are used in data compression techniques to encode integer sequences efficiently.**Cryptography:**Fibonacci numbers can be utilized in cryptographic algorithms to generate secure keys and random sequences.

### Summary

In this tutorial, we saw various methods to generate the Fibonacci series in Python. Every method has its associated advantages and disadvantages. To understand the application of any method depends on practice. The more you practice the more your concepts get furnished.