[Tutor] Fibonacci series(perhaps slightly off topic)
Emil
kuffert_med_hat at hotmail.com
Thu Jul 3 17:27:10 CEST 2008
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.
_________________________________________________________________
Connect to the next generation of MSN Messenger
http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline
More information about the Tutor
mailing list