# Fibonacci series recursion error

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Sat Apr 30 04:14:46 EDT 2011

```Am 30.04.2011 09:43 schrieb harrismh777:

> On the other hand, I am very much interested in "yield," because of its
> obvious persistent state, On the other hand, I don't like you fib()
> function because it does not encapsulate the fib generator. I suppose
> you are considering whatever module is holding the fib() code as the
> encapsulation, but I thought the idea from the OP was to create a
> generator that could be called and return a list... this is a little goofy:
> list(islice(fib(), X))
>
> when what was wanted is:
>
> list = fib(X)

You can have both with the following:

def fib(max=None):
a = b = 1
while max is None or a <= max:
yield a
a, b = b, a+b
from itertools import islice
flist = list(islice(fib(), 100000))

flist2 = list(fib(100000))

or - if even the latter is unwanted -

def fibgen(max=None):
a = b = 1
while max is None or a <= max:
yield a
a, b = b, a+b

def fib(max=None, num=None):
if num is None:
return list(fibgen(max=max))
else:
from itertools import islice
return list(islice(fib(max=max), num))

Thomas

```