Created
June 11, 2019 17:07
-
-
Save spajak/cbec2a351bb7399f6a4a62c6dc8aeebb to your computer and use it in GitHub Desktop.
Fibonacci sequence iterator in Python
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
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