Last active
October 13, 2015 10:57
-
-
Save sgammon/4185115 to your computer and use it in GitHub Desktop.
Efficient Fibonacci Sequence generator 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
# -*- coding: utf-8 -*- | |
''' | |
Code Samples: Fibonacci Sequence | |
Author: Sam Gammon <[email protected]> | |
Description: | |
Recursively generates items in the Fibonacci Sequence, up to kw/positional arg `limit`. | |
Supports starting anywhere in the sequence, assuming `previous` and `current` are truly | |
part of the Fibonacci set. | |
''' | |
def fib(limit=10000, previous=1, current=0): | |
''' Generate items in the fibonacci sequence, | |
from the pair (`previous`, `current`) to `limit`. | |
All parameters are ``int``s, and one need only | |
pass a 'limit,' which is also optional and defaults | |
to ``10,000``. | |
:param limit: Value limit to generate numbers to. | |
:param previous: Former value in the moving window. | |
:param current: Latter value in the moving window. | |
:returns: ``int`` values that are successively greater | |
members of the Fibonacci sequence. ''' | |
if limit and (current >= limit): raise StopIteration() | |
yield previous + current | |
for next in fib(limit, current, (previous + current)): | |
yield next | |
if __name__ == '__main__': | |
for i in fib(): print i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment