Skip to content

Instantly share code, notes, and snippets.

@gchiam
Created July 11, 2014 02:27
Show Gist options
  • Save gchiam/8e35e66e2c3a6582f506 to your computer and use it in GitHub Desktop.
Save gchiam/8e35e66e2c3a6582f506 to your computer and use it in GitHub Desktop.
Python yield example - Fibonacci
"""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,
print
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment