[Tutor] generators?

dman dsh8290@rit.edu
Fri, 30 Nov 2001 10:23:07 -0500


On Thu, Nov 29, 2001 at 11:43:14PM -0500, dman wrote:
...

| def fib() :
|     """
|     Generate the fibonacci series
|     """
| 
|     prev2 = 1
|     prev1 = 1
|     while 1 :
|         next = prev1 * prev2
|         prev2 = prev1
|         prev1 = next
| 
|         yield next

As you can see here I messed up the math.  This would return '1'
forever.


def fib() :
    # the first two values in the sequence
    prev2 = 0
    yield prev2 
    prev1 = 1
    yield prev1

    while 1 :
        next = prev1 + prev2
        prev2 = prev1
        prev1 = next

        yield next


If I test it this time :

>>> for i in fib() :
...   print i ,
...   time.sleep( 1 )
... 
0 1 1 2 3 5 8 13
Traceback (most recent call last):
  File "<stdin>", line 3, in ?
  KeyboardInterrupt
>>> 

That looks better :-).  (BTW, without the sleep the numbers get real
big real fast!)

-D

-- 

the nice thing about windoze is - it does not just crash,
it displays a dialog box and lets you press 'ok' first.