Fibonacci series recursion error

harrismh777 harrismh777 at charter.net
Sat Apr 30 22:41:07 CEST 2011


Thomas Rachel wrote:
> 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))

Yes, yes, yes... but what I realized was really bugging me is the import 
of islice... I don't like it... ;  however, I agree that we should 
combine Otten's ideas with my own... good collaboration... but like this:

fib3.py 'yields' within a 'for'  (better than the while for a couple of 
reasons I'll include later after the rebuttal...  anyway because the def 
with the yield compiles into an iterable we can take advantage of the 
iteration protocol directly with the 'for' to either print the list over 
time, or to get the list and save it... as so:

====================begin fib3.py=======================================
!/home/marcus/bin/python3
def fib(n=1):
     a = b = 1
     for j in range(n):
         yield a
         a, b = b, a+b

# to get the elements of the generator over time
for n in fib(10):
     print(n, end=' ')

# or, get the whole list and save it
flist=[]
for n in fib(10):
     flist.append(n)

====================end fib3.py=========================================

Or, same technique generally, we can take advantage of the fact that the 
def with a 'yield' compiles into an iterable with a next method... all 
part of the iteration protocal of python...   next in 2.6,  and __next__ 
in 3.2 /   ... and the next(N) function provided kindly by somone for 
convenience sake meaning N.next() in 2.6 and N.__next__() in 3.2 /
In the following code I've included a try block to catch the iteration 
protocol's StopIteration error so that we can use the venerable 'while 
True' do forever coding style outside the fib() generator. Again, we can 
print the elements over time, or we can save the list as a whole for 
later use, as so:

====================begin fib4.py=======================================
#!/home/marcus/bin/python3
def fib(n=1):
     a = b = 1
     for j in range(n):
         yield a
         a, b = b, a+b

# get the elements of the generator over time
X = fib(10)
while True:
     try:
         print(next(X), end=' ')
     except StopIteration:
         break

# or, get the whole list and save it
Y = fib(10)
flist=[]
while True:
     try:
         flist.append(next(Y))
     except StopIteration:
         break

====================end fib4.py=========================================



More information about the Python-list mailing list