[Tutor] Fibonacci series(perhaps slightly off topic)

John Fouhy john at fouhy.net
Thu Jul 3 02:59:39 CEST 2008

On 03/07/2008, Emil <kuffert_med_hat at hotmail.com> wrote:
>  I have created a class called Fibs which allow you to access a specific number in the
> Fibonacci series(http://en.wikipedia.org/wiki/Fibonacci_number) But it seems to me that it
> is a bit inefficient, any suggestions on how to make it more efficient?

Does this behaviour seem correct to you? --

>>> class Fibs(object):
...        def __init__(self):
...                self.fibsseq = [0, 1]
...        def __getitem__(self, key):
...                for i in xrange(key):
...                        self.fibsseq.append(self.fibsseq[-1] +
...                return self.fibsseq[key]
>>> f = Fibs()
>>> f[1]
>>> f[1]
>>> f[1]
>>> f.fibsseq
[0, 1, 1, 2, 3]

Maybe if I examine the first Fibonacci number a few hundred times:

>>> ones = [f[1] for i in xrange(500)]
>>> len(f.fibsseq)

Hmm, that's a lot of numbers to calculate when we're only looking at
the first element in the sequence..

(by the way: you might want to replace 'print' with 'return' in your
definition of __getitem__)

(by the way 2: if you follow the above code, and then display
f.fibsseq, you may see some nice curves caused by the " " between each
number.  Aren't fibonacci numbers wonderful :-) )


More information about the Tutor mailing list