iterator.py 777 B

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