|
| 1 | +# Iterators |
| 2 | +An iterator is a nice concept since it allows to create laze sequences, |
| 3 | +i.e., sequences that have elements that are computed only when they are |
| 4 | +requested by retrieving the enxt element. |
| 5 | + |
| 6 | +Python allows for two basic ways to implement iterators, either as |
| 7 | +function that have a LHS yield statements, or as class that implement |
| 8 | +an `__iter__` and a `next` method. |
| 9 | + |
| 10 | +However, often it is not necessary to implements iterators from scratch, |
| 11 | +often they can be constructed by using the Python standard library's |
| 12 | +`itertools` functionality. |
| 13 | + |
| 14 | +## What is it? |
| 15 | +1. `accumulator.py`: illustrates the use of `itertools`'s `accumulate` in |
| 16 | + for various types of data and operators. |
| 17 | +1. `count_down.py`: simple illustration of a class that implements an |
| 18 | + iterable. |
| 19 | +1. `event_generate.py`: a sequence of `Event` objects is generated by |
| 20 | + an instance of the `EventIter` class. Events have a type, a start time, |
| 21 | + and a duration. Events of the same type can not overlap. The |
| 22 | + `EventIter` constructor takes a list of event types, and a start time. |
| 23 | + It generates sequence of random type, start time and duration, until an |
| 24 | + event is generated that last later than the stop time. |
| 25 | +1. `generators.ipynb`: Jupyter notebook illustrating generators. |
| 26 | +1. `people.py`: illustration of `itertools`'s `groupby`, and `operator`'s |
| 27 | + `attrgetter` methods. Note that `groupby` does not reorder the |
| 28 | + original iterators element, but only groups consecutive elements that |
| 29 | + have the same key. |
| 30 | +1. `primes.py`: this script will generate the sequence of prime numbers |
| 31 | + until it is interupted. The iterator is implemented by a function with |
| 32 | + a `yield` statement. |
| 33 | +1. `primes_multiple_calls.py`: illustrates that a function with `yield` |
| 34 | + instantiates a generator when called, and hence "starts over" for |
| 35 | + each `for`-loop. |
| 36 | +1. `primes_itertools.py`: this script also generates a potentially |
| 37 | + infinite sequence of prime numbers, but it is implemented using |
| 38 | + the `count` function of the `itertools` module in Python's standard |
| 39 | + library, as well as the `filter` function. |
| 40 | +1. `dataset.py`: illustrates the `__iter__` and `__next__` methods, as well |
| 41 | + as utilities of the `operator` module. |
| 42 | +1. `generating_data.py`: a retake of the data geenration script in |
| 43 | + Fundamentals, now using `itertools` and built-in Python functional |
| 44 | + features. |
0 commit comments