Skip to content

Instantly share code, notes, and snippets.

@spajak
Created June 11, 2019 17:07
Show Gist options
  • Save spajak/cbec2a351bb7399f6a4a62c6dc8aeebb to your computer and use it in GitHub Desktop.
Save spajak/cbec2a351bb7399f6a4a62c6dc8aeebb to your computer and use it in GitHub Desktop.
Fibonacci sequence iterator in Python
class Fib:
"""Iterator that yields numbers in the Fibonacci sequence"""
def __init__(self, max):
self.max = max
def __iter__(self):
self.a = 0
self.b = 1
return self
def __next__(self):
fib = self.a
if fib > self.max:
raise StopIteration
self.a, self.b = self.b, self.a + self.b
return fib
print(tuple(x for x in Fib(100)))
'''
OUTPUT:
(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment