Created
July 11, 2014 02:27
-
-
Save gchiam/8e35e66e2c3a6582f506 to your computer and use it in GitHub Desktop.
Python yield example - Fibonacci
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
"""Print Fibonacci series using generator""" | |
import argparse | |
import textwrap | |
def fibonacci(number): | |
"""Fibonacci series generator""" | |
previous, current = 0, 1 | |
counter = 0 | |
while counter < number: | |
yield current | |
previous, current = current, current + previous | |
counter += 1 | |
def main(): | |
"""Main function""" | |
parser = argparse.ArgumentParser( | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
description='Print Fibonacci series', | |
epilog=textwrap.dedent('''\ | |
$python fibonacci.py 10 | |
1 1 2 3 5 8 13 21 34 55 | |
''') | |
) | |
parser.add_argument( | |
'number', | |
metavar='N', | |
type=int, | |
help='Size of Fibonacci series') | |
args = parser.parse_args() | |
for num in fibonacci(args.number): | |
print num, | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment