iterator.py 915 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
  4. Implementation of the iterator pattern with a generator"""
  5. def count_to(count):
  6. """Counts by word numbers, up to a maximum of five"""
  7. numbers = ["one", "two", "three", "four", "five"]
  8. # enumerate() returns a tuple containing a count (from start which
  9. # defaults to 0) and the values obtained from iterating over sequence
  10. for pos, number in zip(range(count), numbers):
  11. yield number
  12. # Test the generator
  13. count_to_two = lambda: count_to(2)
  14. count_to_five = lambda: count_to(5)
  15. print('Counting to two...')
  16. for number in count_to_two():
  17. print(number, end=' ')
  18. print()
  19. print('Counting to five...')
  20. for number in count_to_five():
  21. print(number, end=' ')
  22. print()
  23. ### OUTPUT ###
  24. # Counting to two...
  25. # one two
  26. # Counting to five...
  27. # one two three four five