iterator.py 771 B

1234567891011121314151617181920212223242526
  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 defaults to 0) and the values obtained from iterating over sequence
  7. for pos, number in zip(range(count), numbers):
  8. yield number
  9. # Test the generator
  10. count_to_two = lambda : count_to(2)
  11. count_to_five = lambda : count_to(5)
  12. print('Counting to two...')
  13. for number in count_to_two():
  14. print(number, end=' ')
  15. print()
  16. print('Counting to five...')
  17. for number in count_to_five():
  18. print(number, end=' ')
  19. print()