[Tutor] fibonacci
Gregor Lingl
glingl@aon.at
Fri Feb 14 12:13:24 2003
Bob Gailer schrieb:
> At 01:24 PM 2/14/2003 +0100, Gregor Lingl wrote:
>
>> def fib1liner(n, f=[0,1]):
>> return(n+1>len(f))and[(lambda x:f.append(f[-2]+f[-1]))(i)for i in
>> range(n+1-len(f))]and 0 or f[n]
>
>
> Thanks for a really great example of what can be done using and, or,
> comprehension. FWIW this can be simplified to:
>
> def fib1liner(n, f=[0,1]):
> return n>1 and[(lambda:f.append(f[-2]+f[-1]))()for i in
> range(n-1)]and 0 or f[n]
>
Thanks for you compression - concerning the lambda expression.
However, your oneliner is not exactly eqivalent to the original:
with every call for n > 1 it computes n-1 new fibonacci numbers, while
the original
version uses the fact, that f - as a mutable object - after every call
remains changed.
so after you have computed fib1liner(20), f contains all
fibonacci-numbers up to the 20th.
Every following call with n<20 needs not to compute anything new.
Advantages: (1) no unnecessary computing time
(2) no unnecessary memory used
Gregor
P.S. What does FWIW mean?
>
> Bob Gailer
> mailto:ramrom@earthling.net
> 303 442 2625
>
>------------------------------------------------------------------------
>
>
>---
>Outgoing mail is certified Virus Free.
>Checked by AVG anti-virus system (http://www.grisoft.com).
>Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003
>
>