Created
February 20, 2012 01:36
-
-
Save dustingetz/1867106 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from itertools import islice | |
def fib_gen(): | |
a, b = 0, 1 | |
while 1: | |
yield a | |
a, b = b, a + b | |
assert [0, 1, 1, 2, 3, 5, 8] == list(islice(fib_gen(), 7)) | |
def ftake(fnext, last): | |
return [fnext() for _ in xrange(last)] | |
def fib_gen2(): | |
global a; a = 1 | |
global b; b = 1 | |
def next(): | |
global a; global b; | |
r = a | |
a, b = b, a + b | |
return r | |
return next | |
assert [1,1,2,3,5] == ftake(fib_gen2(), 5) | |
class fib_gen3: | |
def __init__(self): | |
self.a, self.b = 1, 1 | |
def __call__(self): | |
r = self.a | |
self.a, self.b = self.b, self.a + self.b | |
return r | |
assert [1,1,2,3,5] == ftake(fib_gen3(), 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment