Skip to content

Instantly share code, notes, and snippets.

@kojiromike
Created March 29, 2018 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kojiromike/7e2f6fcb72436398b0ac9b3d0f037493 to your computer and use it in GitHub Desktop.
Save kojiromike/7e2f6fcb72436398b0ac9b3d0f037493 to your computer and use it in GitHub Desktop.
#!/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