Home
Python
Fibonacci Sequence
Updated Mar 20, 2023
Dot Net Perls
Fibonacci. In 1202, Fibonacci published his sequence. The Fibonacci sequence helped with bookkeeping and charging interest on loans.
Algorithms. We can compute this sequence iteratively, with no recursion. To display a list of Fibonacci numbers, we can make just one iteration through them.
First program. To compute the Fibonacci sequence, we must sum the previous two numbers. This value becomes the next number for the sequence.
Info A temporary variable "temp" is used to store the previous value for later use.
Note We use range() to loop over the entire numeric range to the desired Fibonacci number.
while
Note 2 We do not need recursion for a Fibonacci sequence. Iteration, with a temporary variable, works as well—and is likely faster.
def fibonacci(n): a = 0 b = 1 for i in range(0, n): temp = a a = b b = temp + b return a # Display the first 15 Fibonacci numbers. for c in range(0, 15): print(fibonacci(c))
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Display. This method displays Fibonacci numbers as it goes along. For creating a list of Fibonacci numbers, this approach is faster. Just change the "print" statement to a list append call.
Tip Using lookup tables or "memoizing" math computations is usually faster for nontrivial requirements.
Memoize
Tip 2 To access small Fibonacci numbers quickly, store them in a list and just reuse that list when required.
String List
def fibonacci2(n): a = 0 b = 1 for i in range(0, n): # Display the current Fibonacci number. print(a) temp = a a = b b = temp + b return a # Directly display the numbers. fibonacci2(15)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
A summary. Fibonacci sequences are often used to predict financial markets. Whether anyone can predict financial markets reliably is debatable.
The sequence itself, though, is simple and easy to iteratively compute. Recursion is not necessary. Using a cache (like a list) of numbers would be worthwhile for performance.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 20, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen