summaryrefslogtreecommitdiff
path: root/advanced_python/16_generators.ipyml
blob: bf6e4273a8bbe834aa05d8130e3abe652723e9a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
cells:

- markdown: |
    # Advanced Python: Iterators and Generators

    ### Prabhu Ramachandran
    ### The FOSSEE Python group &
    ### Department of Aerospace Engineering
    ### IIT Bombay

  metadata:
    slideshow:
      slide_type: slide

- markdown: |
    ## Background

    - Container objects present a similar interface
    - They can all be looped over using `for`

  metadata:
    slideshow:
      slide_type: slide

- code: |
    for i in [1, 2, 3]:
        print(i)

    for key in {'a': 1, 'b': 2}:
        print(key)

    for char in 'hello world':
        print(char)

    for line in open('file.txt'):
        print(line, end='')

- markdown: |
    ## Background

    - Similar interface for different objects
    - These objects are all **iterable**
    - They are all **iterators**

  metadata:
    slideshow:
      slide_type: subslide

- markdown: |
    ## Introduction

    - This is a powerful feature/abstraction
    - Easy to create your own iterators
    <br/>
    <br/>

  metadata:
    slideshow:
      slide_type: slide

- markdown: |
    - A **generator** makes it easy to create an iterator
    - How would you write a `range` function?
    <br/>
    <br/>

    - Use the `yield` keyword

  metadata:
    slideshow:
      slide_type: fragment

- code: |
    def counter(n):
        count = 0
        while count < n:
            yield count
            count += 1

  metadata:
    slideshow:
      slide_type: slide

- code: |
    c = counter(2)

- code: |
    next(c)

- code: |
    next(c)

- code: |
    next(c)

- code: |
    for i in counter(5):
        print(i)

  metadata:
    slideshow:
      slide_type: slide

- markdown: |
    ## Observations

    - Note that `yield` resumes the function
    - The function/method remembers its state
    - It can yield any object
    - An empty `yield` is also acceptable
    - You can have multiple yields

  metadata:
    slideshow:
      slide_type: slide

- code: |
    def infinite_generator():
        while True:
            yield

  metadata:
    slideshow:
      slide_type: fragment

- markdown: |
    ## Exercise: simple generator

    Write a simple generator that generates the first `n` odd numbers. Call this
    function `odd(n)`.

  metadata:
    slideshow:
      slide_type: slide

- code: |
    for x in odd(5):
        print(x)

- markdown: |
    ## Solution

  metadata:
    slideshow:
      slide_type: slide

- code: |
    def odd(n):
        for i in range(n):
            yield 2*i + 1

- markdown: |
    ## Exercise: Fibonacci generator

    Write a simple generator that returns the first `n` numbers of the Fibonacci
    sequence, call this function `fib(n)`.

  metadata:
    slideshow:
      slide_type: slide

- code: |
    for x in fib(10):
        print(x)

- markdown: |
    ## Solution

  metadata:
    slideshow:
      slide_type: slide

- code: |
    def fib(n):
        a, b = 0, 1
        yield 0
        for i in range(n-1):
            yield b
            a, b = b, a + b

- markdown: |
    ## Creating iterable objects

    - What if you want to create an object that is iterable?
    - Overload the `__iter__` and/or `__next__` methods.
    - Recall our `Zoo` class?

  metadata:
    slideshow:
      slide_type: slide

- code: |
    class Zoo:
        def __init__(self, *animals):
            self.animals = list(animals)

- markdown: |
    We want the following to work,

  metadata:
    slideshow:
      slide_type: slide

- code: |
    c = Animal('crow')
    m = Mammal('dog')
    z = Zoo(c, m)

    for animal in z:
        animal.greet()

- markdown: |
    ## Making `Zoo` iterable

    - Overload the `__iter__` to return an iterable
    - An iterable should have a `__next__` method

  metadata:
    slideshow:
      slide_type: slide

- code: |
    class Zoo:
        def __init__(self, *animals):
            self.animals = list(animals)

        def __iter__(self):
            return iter(self.animals)

- code: |
    class Animal(object):
        def __init__(self, name):
            self.name = name
        def greet(self):
            print(self.name, "says hi!")

    class Mammal(Animal):
        pass

  metadata:
    slideshow:
      slide_type: slide

- code: |
    c = Animal('crow')
    m = Mammal('dog')
    z = Zoo(c, m)

    for animal in z:
        animal.greet()

  metadata:
    slideshow:
      slide_type: slide

- markdown: |
    ## Observations

    - Just returns `iter(self.animals)`
    - `self.animals` is a `list` and calling `iter` makes it an iterator

  metadata:
    slideshow:
      slide_type: slide

- markdown: |
    ## A more complex example

    - What if we cannot just return an internal list?
    - We must provide a `__next__` method
    - To stop the iteration: `raise StopIteration`

  metadata:
    slideshow:
      slide_type: slide

- code: |
    class SimpleRange:
        def __init__(self, n):
            self.n = n
            self.count = 0
        def __iter__(self):
            return self
        def __next__(self):
            if self.count == self.n:
                raise StopIteration
            self.count += 1
            return self.count

  metadata:
    slideshow:
      slide_type: subslide

- code: |
    r = SimpleRange(5)
    for i in r:
        print(i)

  metadata:
    slideshow:
      slide_type: subslide

- markdown: |
    ## Observations

    - Useful when you want an object to be iterable
    - Notice the `__next__` method
    - Notice the `raise StopIteration`
    - Easier to use functions/methods with `yield`

  metadata:
    slideshow:
      slide_type: slide

- markdown: |
    ## Summary

    - Easy to use and write
    - Allows one to abstract a loop
    - `yield` for functions and methods
    - Overload `__iter__, __next__` for objects

  metadata:
    slideshow:
      slide_type: slide

- markdown: |
    ## Exercise: Fibonacci object

    Create a class that when instantiated with an argument `n` can be used as a
    sequence of the first `n` numbers of the Fibonacci sequence, call this
    class `Fib`.

  metadata:
    slideshow:
      slide_type: slide

- code: |
    f = Fib(5)
    for x in f:
        print(x)

- markdown: |
    ## Solution

  metadata:
    slideshow:
      slide_type: slide

- code: |
    class Fib:
        def __init__(self, n):
            self.count = n
            self.a, self.b = 0, 1
        def __iter__(self):
            return self
        def __next__(self):
            if self.count == 0:
                raise StopIteration
            old = self.a
            self.count -= 1
            self.a, self.b = self.b, self.a + self.b
            return old

- code: |
    f = Fib(10)
    for i in f:
        print(i)

  metadata:
    slideshow:
      slide_type: slide

# The lines below here may be deleted if you do not need them.
# ---------------------------------------------------------------------------
metadata:
  celltoolbar: Slideshow
  kernelspec:
    display_name: Python 3
    language: python
    name: python3
  language_info:
    codemirror_mode:
      name: ipython
      version: 3
    file_extension: .py
    mimetype: text/x-python
    name: python
    nbconvert_exporter: python
    pygments_lexer: ipython3
    version: 3.5.2
  rise:
    scroll: true
    transition: none
nbformat: 4
nbformat_minor: 2