HomeSearch

Python Fibonacci Sequence

Compute Fibonacci sequences with an iterative method. Use a for-loop and the range sequence.

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.

Variable: A temporary variable "temp" is used to store the previous value for later use.

Range: We use range() to loop over the entire numeric range to the desired Fibonacci number.

Range

Note: We do not need recursion for a Fibonacci sequence. Iteration, with a temporary variable, works as well—and is likely faster.

Python program that computes Fibonacci sequence 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)) Output 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

List: To access small Fibonacci numbers quickly, store them in a list and just reuse that list when required.

List
Python program that displays Fibonacci sequence 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) Output 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.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.