Fibonacci series recursion error

Peter Otten __peter__ at web.de
Sat Apr 30 02:14:56 EDT 2011


harrismh777 wrote:

> def fib(i=1):
>      a=1;n=1;l=[]
>      for j in range(0,i):
>          l.append(a)
>          p=a;a=n;n=p+a

Hm, did you run out of newlines?

>      return l
> 
> list=fib(7)
> 
> 
> 
> ... and the above, is how I would actually code it....
> 
> 
> 
> 

Nah, that can't be it ;)

For the record, the one true way to implement the Fibonacci series in Python 
is

>>> def fib():
...     a = b = 1
...     while True:
...             yield a
...             a, b = b, a+b # look ma, no temporary variable
...
>>> from itertools import islice
>>> list(islice(fib(), 20))
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 
4181, 6765]





More information about the Python-list mailing list