On 03/07/2008, Emil <[EMAIL PROTECTED]> 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] +
self.fibsseq[-2])
...                return self.fibsseq[key]
...
>>> f = Fibs()
>>> f[1]
1
>>> f[1]
1
>>> f[1]
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)
505

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 :-) )

-- 
John.
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to