Created
March 29, 2018 03:25
-
-
Save kojiromike/7e2f6fcb72436398b0ac9b3d0f037493 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/env python | |
"""A few different (but really the same) ways to create the Fibonacci sequence.""" | |
from pprint import pprint as pp | |
def fibs1(): | |
'''Generate the Fibonacci sequence.''' | |
x, y = 0, 1 | |
while True: | |
x, y = x + y, x | |
yield x | |
def fibs2(): | |
'''Generate the Fibonacci sequence using a mutable default arg.''' | |
def _fib(x=[0, 1]): | |
x.reverse() | |
x[0] = sum(x) | |
return x[0] | |
while True: | |
yield _fib() | |
def fibs3(): | |
'''Generate the Fibonacci sequence by flipping a list.''' | |
x = [0, 1] | |
while True: | |
x.reverse() | |
x[0] = sum(x) | |
yield x[0] | |
d, e, f = fibs1(), fibs2(), fibs3() | |
pp([next(d) for i in range(12)]) | |
pp([next(e) for i in range(12)]) | |
pp([next(f) for i in range(12)]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment