[Tutor] Fibonacci series(perhaps slightly off topic)

Mark Tolonen metolone+gmane at gmail.com
Fri Jul 4 03:55:55 CEST 2008


You can actually remove the try/except, because if the calculation 
key-len(self.fibsseq)+1 <= 0 the for loop won't execute.  The for loop will 
make sure self.fibsseq is long enough to satisify the return 
self.febsseq[key] access:

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

-Mark


"Emil" <kuffert_med_hat at hotmail.com> wrote in message 
news:BAY112-W3337F0310991A977DF9E15A3980 at phx.gbl...

Hey John thank you for your reply. I came up with this code, it is not 
elegant( yet) but i would say that it is more efficient :)




class Fibs(object):

def __init__(self):
self.fibsseq = [0,1]

def __getitem__(self, key):
try:
return self.fibsseq[key]
except IndexError:
for i in xrange(key-len(self.fibsseq)+1):
self.fibsseq.append(self.fibsseq[-1] + self.fibsseq[-2])
return self.fibsseq[key]





----------------------------------------
> Date: Thu, 3 Jul 2008 12:59:39 +1200
> From: john at fouhy.net
> To: kuffert_med_hat at hotmail.com
> Subject: Re: [Tutor] Fibonacci series(perhaps slightly off topic)
> CC: tutor at python.org
>
> On 03/07/2008, Emil  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.




More information about the Tutor mailing list