How to write the Fibonacci Sequence? How to write the Fibonacci Sequence? python python

How to write the Fibonacci Sequence?


There is lots of information about the Fibonacci Sequence on wikipedia and on wolfram. A lot more than you may need. Anyway it is a good thing to learn how to use these resources to find (quickly if possible) what you need.

Write Fib sequence formula to infinite

In math, it's given in a recursive form:

fibonacci from wikipedia

In programming, infinite doesn't exist. You can use a recursive form translating the math form directly in your language, for example in Python it becomes:

def F(n):    if n == 0: return 0    elif n == 1: return 1    else: return F(n-1)+F(n-2)

Try it in your favourite language and see that this form requires a lot of time as n gets bigger. In fact, this is O(2n) in time.

Go on on the sites I linked to you and will see this (on wolfram):

Fibonacci Equation

This one is pretty easy to implement and very, very fast to compute, in Python:

from math import sqrtdef F(n):    return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))

An other way to do it is following the definition (from wikipedia):

The first number of the sequence is 0, the second number is 1, and each subsequent number is equal to the sum of the previous two numbers of the sequence itself, yielding the sequence 0, 1, 1, 2, 3, 5, 8, etc.

If your language supports iterators you may do something like:

def F():    a,b = 0,1    while True:        yield a        a, b = b, a + b

Display startNumber to endNumber only from Fib sequence.

Once you know how to generate Fibonacci Numbers you just have to cycle trough the numbers and check if they verify the given conditions.

Suppose now you wrote a f(n) that returns the n-th term of the Fibonacci Sequence (like the one with sqrt(5) )

In most languages you can do something like:

def SubFib(startNumber, endNumber):    n = 0    cur = f(n)    while cur <= endNumber:        if startNumber <= cur:            print cur        n += 1        cur = f(n)

In python I'd use the iterator form and go for:

def SubFib(startNumber, endNumber):    for cur in F():        if cur > endNumber: return        if cur >= startNumber:            yield curfor i in SubFib(10, 200):    print i

My hint is to learn to read what you need. Project Euler (google for it) will train you to do so :PGood luck and have fun!


Efficient Pythonic generator of the Fibonacci sequence

I found this question while trying to get the shortest Pythonic generation of this sequence (later realizing I had seen a similar one in a Python Enhancement Proposal), and I haven't noticed anyone else coming up with my specific solution (although the top answer gets close, but still less elegant), so here it is, with comments describing the first iteration, because I think that may help readers understand:

def fib():    a, b = 0, 1    while True:            # First iteration:        yield a            # yield 0 to start with and then        a, b = b, a + b    # a will now be 1, and b will also be 1, (0 + 1)

and usage:

for index, fibonacci_number in zip(range(10), fib()):     print('{i:3}: {f:3}'.format(i=index, f=fibonacci_number))

prints:

  0:   0  1:   1  2:   1  3:   2  4:   3  5:   5  6:   8  7:  13  8:  21  9:  34 10:  55

(For attribution purposes, I recently noticed a similar implementation in the Python documentation on modules, even using the variables a and b, which I now recall having seen before writing this answer. But I think this answer demonstrates better usage of the language.)

Recursively defined implementation

The Online Encyclopedia of Integer Sequences defines the Fibonacci Sequence recursively as

F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1

Succinctly defining this recursively in Python can be done as follows:

def rec_fib(n):    '''inefficient recursive function as defined, returns Fibonacci number'''    if n > 1:        return rec_fib(n-1) + rec_fib(n-2)    return n

But this exact representation of the mathematical definition is incredibly inefficient for numbers much greater than 30, because each number being calculated must also calculate for every number below it. You can demonstrate how slow it is by using the following:

for i in range(40):    print(i, rec_fib(i))

Memoized recursion for efficiency

It can be memoized to improve speed (this example takes advantage of the fact that a default keyword argument is the same object every time the function is called, but normally you wouldn't use a mutable default argument for exactly this reason):

def mem_fib(n, _cache={}):    '''efficiently memoized recursive function, returns a Fibonacci number'''    if n in _cache:        return _cache[n]    elif n > 1:        return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))    return n

You'll find the memoized version is much faster, and will quickly exceed your maximum recursion depth before you can even think to get up for coffee. You can see how much faster it is visually by doing this:

for i in range(40):    print(i, mem_fib(i))

(It may seem like we can just do the below, but it actually doesn't let us take advantage of the cache, because it calls itself before setdefault is called.)

def mem_fib(n, _cache={}):    '''don't do this'''    if n > 1:          return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))    return n

Recursively defined generator:

As I have been learning Haskell, I came across this implementation in Haskell:

fib@(0:tfib) = 0:1: zipWith (+) fib tfib

The closest I think I can get to this in Python at the moment is:

from itertools import teedef fib():    yield 0    yield 1    # tee required, else with two fib()'s algorithm becomes quadratic    f, tf = tee(fib())     next(tf)    for a, b in zip(f, tf):        yield a + b

This demonstrates it:

[f for _, f in zip(range(999), fib())]

It can only go up to the recursion limit, though. Usually, 1000, whereas the Haskell version can go up to the 100s of millions, although it uses all 8 GB of my laptop's memory to do so:

> length $ take 100000000 fib 100000000

Consuming the iterator to get the nth fibonacci number

A commenter asks:

Question for the Fib() function which is based on iterator: what if you want to get the nth, for instance 10th fib number?

The itertools documentation has a recipe for this:

from itertools import islicedef nth(iterable, n, default=None):    "Returns the nth item or a default value"    return next(islice(iterable, n, None), default)

and now:

>>> nth(fib(), 10)55


Why not simply do the following?

x = [1,1]for i in range(2, 10):      x.append(x[-1] + x[-2]) print(', '.join(str(y) for y in x))