For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
The Fibonacci series is one of the most fascinating mathematical sequences with applications spanning from nature and art to computer algorithms and financial markets. This tutorial will help you implement the Fibonacci series in Python using multiple methods. It covers basic iterative techniques as well as more advanced optimization strategies for better performance. Whether you're a beginner or experienced, you'll find useful examples to improve your programming skills.
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. The sequence typically starts with 0 and 1, and continues infinitely: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...
Mathematically, it can be defined as:
This simple recursive definition creates a pattern commonly found in nature, like leaves, pinecones, and sunflowers. You can also see these spiral patterns in galaxies, showing how often Fibonacci appears in the real world.
Expand your expertise in AI with an Executive Programme, perfect for leaders in tech-driven industries.
Let's compare their strengths and limitations by exploring different methods to implement the Fibonacci sequence in Python.
Problem Statement: Generate the first n numbers in the Fibonacci sequence using an iterative approach, which is ideal for larger sequences due to its efficiency.
def fibonacci_iterative(n):
# Initialize the first two terms
a, b = 0, 1
# Check if n is valid
if n <= 0:
return "Please enter a positive integer"
elif n == 1:
return [0]
# Generate Fibonacci sequence
fibonacci_sequence = [0, 1]
for i in range(2, n):
c = a + b
fibonacci_sequence.append(c)
# Update values for next iteration
a, b = b, c
return fibonacci_sequence
# Print first 10 Fibonacci numbers
result = fibonacci_iterative(10)
print(result)
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The iterative approach avoids redundant calculations by storing each value once, making it the most efficient method with time complexity O(n) and space complexity O(n).
Problem Statement: Implement the Fibonacci sequence using recursion, which directly mirrors the mathematical definition F(n) = F(n-1) + F(n-2) but comes with performance limitations.
def fibonacci_recursive(n):
# Base cases
if n <= 0:
return 0
elif n == 1:
return 1
else:
# Recursive case: sum of previous two Fibonacci numbers
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
# Print first 10 Fibonacci numbers
result = [fibonacci_recursive(i) for i in range(10)]
print(result)
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
While this recursive implementation is elegant and closely follows the mathematical definition, it performs redundant calculations and has exponential time complexity O(2^n), making it impractical for values larger than 40.
Problem Statement: Implement the Fibonacci sequence using dynamic programming to eliminate repetitive calculations by storing previously computed values in an array.
def fibonacci_dp(n):
# Create an array to store Fibonacci numbers
fib = [0] * (n + 1)
# Base cases
if n >= 1:
fib[1] = 1
# Calculate using bottom-up approach
for i in range(2, n + 1):
fib[i] = fib[i - 1] + fib[i - 2]
return fib[:n]
# Print first 10 Fibonacci numbers
result = fibonacci_dp(10)
print(result)
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
The dynamic programming approach builds the solution incrementally from the bottom up, storing each Fibonacci number exactly once and eliminating the redundant calculations of recursion while maintaining O(n) time complexity.
Unlock new career opportunities in data science with an MS online degree and Executive Diploma from IIITB.
For applications requiring frequent Fibonacci calculations, optimization becomes crucial.
Problem Statement: Optimize the recursive Fibonacci implementation using memoization to cache previously calculated values, enabling efficient calculation of large Fibonacci numbers.
def fibonacci_memo(n, memo={}):
# Check if value already calculated
if n in memo:
return memo[n]
# Base cases
if n <= 0:
return 0
elif n == 1:
return 1
# Calculate and store result in memo dictionary
memo[n] = fibonacci_memo(n-1, memo) + fibonacci_memo(n-2, memo)
return memo[n]
# Calculate 50th Fibonacci number efficiently
result = fibonacci_memo(50)
print(f"The 50th Fibonacci number is: {result}")
Output:
The 50th Fibonacci number is: 12586269025
Memoization transforms the inefficient O(2^n) recursive algorithm into an efficient O(n) solution by eliminating redundant calculations while preserving the intuitive recursive structure.
Problem Statement: Implement a clean and efficient Fibonacci calculator using Python's built-in LRU (Least Recently Used) cache decorator to automatically manage memoization.
from functools import lru_cache
@lru_cache(maxsize=None) # No limit on cache size
def fibonacci_cached(n):
# Base cases
if n <= 0:
return 0
elif n == 1:
return 1
else:
# Recursive case with automatic caching
return fibonacci_cached(n-1) + fibonacci_cached(n-2)
# Calculate 100th Fibonacci number efficiently
result = fibonacci_cached(100)
print(f"The 100th Fibonacci number is: {result}")
Output:
The 100th Fibonacci number is: 354224848179261915075
The lru_cache decorator from Python's standard library provides a simple one-line solution for memoization. It automatically handles the caching details and makes the code elegant and production-ready.
The Fibonacci sequence extends far beyond mathematical curiosity, finding applications in various domains:
1. Financial Markets and Trading Algorithms
In technical analysis of financial markets, Fibonacci retracement levels (38.2%, 50%, 61.8%) are widely used to identify potential support and resistance levels. These are derived from the Fibonacci sequence and the golden ratio (approximately 1.618).
Below is a Python function that calculates the Fibonacci retracement levels based on a given high and low price:
def fibonacci_retracement(high_price, low_price):
diff = high_price - low_price
levels = {
"0%": low_price,
"23.6%": low_price + 0.236 * diff,
"38.2%": low_price + 0.382 * diff,
"50%": low_price + 0.5 * diff,
"61.8%": low_price + 0.618 * diff,
"100%": high_price
}
return levels
# Calculate Fibonacci retracement levels for a stock
high = 150.75
low = 120.25
print(fibonacci_retracement(high, low))Output:
{
'0%': 120.25,
'23.6%': 127.448,
'38.2%': 131.901,
'50%': 135.5,
'61.8%': 139.099,
'100%': 150.75
}
2. Computer Science: Search Algorithms and Data Structures
The Fibonacci search technique is used in sorted arrays to find a target value using a divide and conquer approach. It's particularly efficient for arrays that can't be randomly accessed, like tape drives.
3. Natural Patterns and Growth Models
The Fibonacci sequence models many natural phenomena, from the arrangement of leaves on a stem (phyllotaxis) to population growth models. Researchers use these patterns to understand biological systems and predict growth patterns.
The Fibonacci sequence appears widely in nature, forming spiral patterns seen in sunflowers, shells, and galaxies. This visualization, created using Python, shows how the sequence translates into a spiral, revealing the mathematical beauty behind natural growth and design.
To create a simple visualization of the Fibonacci spiral in Python, you can use the matplotlib library:
import matplotlib.pyplot as plt
import numpy as np
def fibonacci_spiral(n):
# Generate Fibonacci numbers
fib = [0, 1]
for i in range(2, n):
fib.append(fib[i-1] + fib[i-2])
# Create the spiral
x = [0] * n
y = [0] * n
angle = 0
for i in range(1, n):
angle += np.pi/2
radius = np.sqrt(fib[i])
x[i] = x[i-1] + radius * np.cos(angle)
y[i] = y[i-1] + radius * np.sin(angle)
# Plot the spiral
plt.figure(figsize=(10, 10))
plt.plot(x, y, 'b-')
plt.plot(x, y, 'ro')
plt.grid(True)
plt.axis('equal')
plt.title('Fibonacci Spiral')
plt.savefig('fibonacci_spiral.png')
plt.show()
# Generate a Fibonacci spiral with 20 points
fibonacci_spiral(20)
Output:
The Fibonacci sequence is a cool example of how math shows up in nature and computer programs. In this tutorial, we explored different ways to create a Fibonacci series program in Python, starting from simple approaches like loops to smarter methods such as memoization and dynamic programming.
Learning how to write a Fibonacci series program in Python not only improves your Python skills but also helps you understand how to design efficient algorithms. Fibonacci numbers appear in many fields like finance, coding challenges, and nature and mastering how to generate them builds a strong foundation for solving a wide range of problems.
As you continue learning Python and algorithms, remember that even a simple concept like the Fibonacci series can reveal deep insights into how math and computing work together!
The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, typically starting with 0 and 1.
The Fibonacci sequence serves as an excellent example for teaching programming concepts like recursion, dynamic programming, and algorithm optimization.
For efficient calculation, use either the iterative approach, dynamic programming, or memoized recursion with the lru_cache decorator.
Yes, using Binet's formula: F(n) = (φⁿ - (1-φ)ⁿ)/√5, where φ is the golden ratio (1.618...), though this may have floating-point precision issues for large n.
As n increases, the ratio of consecutive Fibonacci numbers (F(n+1)/F(n)) approaches the golden ratio (approximately 1.618).
If you only need the nth Fibonacci number (not the entire sequence), you can use just three variables instead of an array, reducing space complexity to O(1).
Yes, the Lucas sequence (2, 1, 3, 4, 7, 11, ...) and other generalized Fibonacci sequences follow the same recursive pattern but start with different values.
Fibonacci heaps, used in certain graph algorithms like Dijkstra's, achieve better amortized running time than binary heaps for certain operations.
Sum the shallow diagonals in Pascal's triangle to obtain Fibonacci numbers.
Python handles arbitrary-precision arithmetic automatically, so Fibonacci calculations won't overflow like they might in languages with fixed-size integers.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918068792934
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.