[Tutor] fibonacci

alan.gauld@bt.com alan.gauld@bt.com
Fri Feb 14 10:41:14 2003


> > Just as an exercise, I was unable to create a one-line 
> recursive fibonacci 
> > generator, but the following works correctly for all values 
> of n greater than 2.
> > 
> > def fib(n):
> >     return (n<5)*(n-2) or fib(n-1) + fib(n-2)

The first bit of this seems convoluted to me, I thought it 
might be clearer thusly(and it works below 2!):

>>> def fib(n):
...   return (( n>1 ) and ( fib(n-1)+fib(n-2) )) or (n==1)
...
>>> for n in range(7): print fib(n),
...
0 1 1 2 3 5 8

Assumes you agree that fib(0) == 0

Only slight modification if you think fib(0) == 1 

Mind you using short circuit evaluation tricks for conditionals 
is never very clear!


> I would not recommend creating a second order (containing two 
> recursive elements e.g. "fib (n - 1)" and  "fib (n - 2)" ) 

I'm curious, why not?
(Aside from performance maybe which is just as true with any 
recursive solution.)

Alan g.