2021-11-22_python-generators.html


001| #:name::Python Generators, part 1
002| #:link::https://thehardcorecoder.com/2021/11/22/python-generators-part-1/
003| #:date::2021-11-22
004| #:code::https://thehardcorecoder.files.wordpress.com/2021/11/generators.zip
005| #:code::
006| def gen0 ():
007|     yield 21
008|     yield 42
009|     yield 63
010|     yield 84
011| 
012| #:code::
013| # Use the generator in a for-loop...
014| for x in gen0():
015|     print(x)
016| print()
017| 
018| # Use the generator to create a list...
019| numbers = list(gen0())
020| print(numbers)
021| print()
022| 
023| #:code::
024| g = gen0()
025| print('#1 next(g) = %d' % next(g))
026| print('#2 next(g) = %d' % next(g))
027| print('#3 next(g) = %d' % next(g))
028| print('#4 next(g) = %d' % next(g))
029| print('#5 next(g) = %d' % next(g))
030| 
031| #:code::
032| def not_a_generator ():
033|     return [21, 42, 63, 84]
034| 
035| #:code::
036| def gen1 (x):
037|     '''A generator function with three items.'''
038|     print(' start')
039|     print(' yield')
040|     yield x+21
041|     print(' resume')
042|     yield x+42
043|     print(' resume')
044|     yield x+63
045|     print(' resume')
046|     yield x+84
047|     print(' return')
048|     return -1
049| 
050| # Use the generator in a for-loop...
051| print('Loop Begin')
052| for n in gen1(37):
053|     print(n)
054| print('Loop End')
055| print()
056| 
057| # Now use it to create a list...
058| print('List Begin')
059| g = list(gen2(3))
060| print(g)
061| print('List Begin')
062| print()
063| 
064| #:code::
065| def also_not_a_generator (x):
066|     nums = [21, 42, 63, 84]
067|     return [x+n for n in nums]
068| 
069| #:code::
070| def gen2 (nbr_chars, base_char='A'):
071|     print(' start')
072|     b = ord(base_char)
073|     # Return a sequence N chars long...
074|     for n in range(nbr_chars):
075|         print(' yield')
076|         yield chr(b+n)
077|         print(' resume')
078|     print(' exit')
079| 
080| # Use the generator in a for-loop...
081| for b in gen2(8,'N'):
082|     print(b)
083| print()
084| 
085| # Use the generator to create a list...
086| g = list(gen2(26))
087| print(g)
088| print()
089| 
090| #:code::
091| def gen_remote_query (**kwargs):
092|     '''Makes internet queries to a database.'''
093|     # ... setup code ...
094|     for qry in queries:
095|         # ...connect to server...
096|         # ...query server...
097|         # ...format results...
098|         yield results
099| 
100| #:code::
101| def stepper (start=0.0, step=1.0):
102|     '''Generator an infinite list of numbers.'''
103|     curr = float(start)
104|     incr = float(step)
105| 
106|     # Loop forever...
107|     while True:
108|         rval = yield curr
109|         # Resume (possible received value)...
110|         if rval is not None:
111|             # Received value is new step value...
112|             incr = float(rval)
113|             continue
114|         # Next increment...
115|         curr += incr
116| 
117| #:code::
118| # Infinite generator in a for-loop; BAD IDEA!...
119| for n in stepper(step=0.25):
120|     print(n)
121| print()
122| 
123| # Infinite generator to create a list; BAD IDEA!...
124| #
125| g = list(stepper(-3.14, step=0.01))
126| print(g)
127| print()
128| 
129| #:code::
130| # Generate [0.000, 0.125, 0.250,... 10.000]...
131| g1 = stepper(step=0.125)
132| for ix in range(81):
133|     n = next(g1)
134|     print('%4d: %5.3f' % (ix+1,n))
135| print()
136| 
137| # Generate [1.00, 0.96, 0.92,... 0.04] (approx)...
138| g2 = stepper(start=1, step=-0.04)
139| counter = next(g2)
140| while 0.0 < counter:
141|     print(counter)
142|     counter = next(g2)
143| 
144| #:code::
145| def points (xmin=-1.0,xmax=1.0, ymin=-1.0,ymax=1.0):
146|     '''Generate infinite random X-Y points.'''
147|     xspan = abs(xmax - xmin)
148|     yspan = abs(ymax - ymin)
149|     while True:
150|         x = xmin + (random() * xspan)
151|         y = ymin + (random() * yspan)
152|         yield (x, y)
153| 
154| pgen = points(0.0,10.0, 0.0,10.0)
155| for ix in range(25):
156|     pt = next(pgen)
157|     print('[%2d]: Next point is %s' % (ix+1,pt))
158| print()
159| 
160| #:name::Python Generators, part 2
161| #:link::https://thehardcorecoder.com/2021/11/23/python-generators-part-2/
162| #:date::2021-11-23
163| #:code::
164| # Calculate and return the next Collatz number...
165| Collatz = lambda n:(0) if abs(n)==1else (((n*3)+1) if (n%2) else (n//2))
166| 
167| # Calculate and return the next Collatz number (pure)...
168| Collatz0 = lambda n:(((n*3)+1) if (n % 2) else (n//2))
169| 
170| #:code::
171| # Same as the first lambda expression above...
172| def Collatz (n):
173|     '''Calculate and return the next Collatz number.'''
174|     if abs(n) == 1:
175|         return 0
176|     if n % 2:
177|         return ((n*3) + 1)
178|     return (n // 2)
179| 
180| #:code::
181| def gen_collatz_1 (n):
182|     '''A Collatz sequence generator function.'''
183|     steps = 1
184|     while 1 < n:
185|         yield n
186|         # Calculate next Collatz number...
187|         n = Collatz(n)
188|         # Count steps as we go...
189|         steps += 1
190|     # Final yield when n==1...
191|     yield n
192|     return steps
193| 
194| # Get the Collatz sequence for N=11...
195| cs = list(gen_collatz_1(11))
196| print(cs)
197| print()
198| 
199| #:code::
200| # Reveal the return value...
201| # Use a number that returns a short sequence...
202| g = gen_collatz_1(8)
203| print('#1 %s' % next(g))
204| print('#2 %s' % next(g))
205| print('#3 %s' % next(g))
206| print('#4 %s' % next(g))
207| print('#5 %s' % next(g))
208| 
209| #:code::
210| def stepper (start=0.0, step=1.0):
211|     '''Generate numbers forever.'''
212|     curr = float(start)
213|     incr = float(step)
214|     while True:
215|         message = yield curr
216|         if message is not None:
217|             # Received value is new step value...
218|             incr = float(message)
219|             continue
220|         # Next increment...
221|         curr += incr
222| 
223| #:code::
224| # Generate a series of increasing steps...
225| delta = 0.015625
226| increment = stepper(0.0, delta)
227| 
228| for ix in range(100):
229|     n = next(increment)
230|     print('%4d: %9.4f' % (ix+1,n))
231|     # Every 10 steps...
232|     if (0 < ix) and (0==(ix % 10)):
233|         # Double the increment...
234|         delta *= 2
235|         print('===== New delta: %.5f' % delta)
236|         # Send the new value to stepper...
237|         increment.send(delta)
238| 
239| print()
240| 
241| #:code::
242| # Two very simple examples of using yield from...
243| def gen0a ():
244|     print(' start')
245|     yield from [21, 42, 63, 84]
246|     print(' exit')
247| 
248| def gen0b (m, n):
249|     print(' start')
250|     yield from enumerate(range(m, n+1))
251|     print(' exit')
252| 
253| # Use a for-loop...
254| for n in gen0a():
255|     print(n)
256| print()
257| 
258| # Generate a list...
259| pairs = list(gen0b(10,20))
260| print(pairs)
261| print()
262| 
263| #:code::
264| def gen_collatz_1 (n):
265|     '''A Collatz sequence generator function.'''
266|     steps = 1
267|     print(' start (%d)' % n)
268|     while 1 < n:
269|         print(' yield1 (%d)' % n)
270|         yield n
271|         print(' resume1')
272|         # Calculate next Collatz number...
273|         n = Collatz(n)
274|         # Counting our steps as we go...
275|         steps += 1
276|     print(' yield2 (%d)' % n)
277|     yield n
278|     print(' resume2')
279|     print(' exit (%d)' % steps)
280|     return steps
281| 
282| def collatz_set_1 (start=1, end=100):
283|     '''Generate a list of Collatz sequences.'''
284|     print(' start (%d,%d)' % (start,end))
285|     for n in range(start,end+1):
286|         print(' yield (%d)' % n)
287|         rv = yield from gen_collatz_1(n)
288|         print(' resume (%s)' % rv)
289|     print(' exit')
290| 
291| for n in collatz_set_1(end=2):
292|     print(n)
293| print()
294| 
295| #:code::
296| def collatz_set_1 (start=1, end=100):
297|     '''Generate a list of Collatz sequences.'''
298|     for n in range(start,end+1):
299|         print(' yield (%d)' % n)
300|         rv = yield from gen_collatz_1(n)
301|         # Return a zero to delimit sequences...
302|         yield 0
303| 
304| #:code::
305| def gen_collatz_sequences (start=1, end=100):
306|     '''Return Collatz sequences.'''
307|     for n in range(start,end+1):
308|         yield list(gen_collatz_1(n))
309| 
310| # Print Collatz sequences from 10 to 20...
311| for cs in gen_collatz_sequences(start=10, end=20):
312|     print(cs)
313| print()
314| 
315| #:code::
316| def all_collatz_sequences (start=1):
317|     '''Return Collatz sequences FOREVER!'''
318|     n = start
319|     while True:
320|         yield list(gen_collatz_2(n))
321|         n += 1
322| 
323| # Print 100 Collatz sequences starting at 11...
324| cs = all_collatz_sequences(11)
325| for ix in range(100):
326|     print('%d: %s' % (ix,next(cs)))
327| 
328| #:name::Python Generators, part 3
329| #:link:https://thehardcorecoder.com/2021/11/24/python-generators-part-3/:
330| #:date::2021-11-24
331| #:code::
332| def gen_collatz_2 (n):
333|     '''Collatz sequence generator function.'''
334|     buf = []
335|     while 1 <= n:
336|         buf.append(n)
337|         yield n
338|         n = Collatz(n)
339|     return buf
340| 
341| g = gen_collatz_2(5)
342| print(next(g))
343| print(next(g))
344| print(next(g))
345| print(next(g))
346| print(next(g))
347| print(next(g))
348| print(next(g))
349| 
350| #:code::
351| g = gen_collatz_2(5)
352| 
353| while True:
354|     try:
355|         print(next(g))
356|     except StopIteration as e:
357|         cs = e.value
358| 
359| print(cs)
360| 
361| #:code::
362| def gen_collatz_3 (cs):
363|     '''Collatz sequence generator. (e.g. cs=[11])'''
364|     while 1 < cs[-1]:
365|         yield cs[-1]
366|         n = Collatz(cs[-1])
367|         cs.append(n)
368|     yield cs[-1]
369| 
370| cs = [13]
371| for n in gen_collatz_3(cs):
372|     if n == 16:
373|         break
374| 
375| print(cs)
376| 
377| #:code::
378| def collatz_seq (n):
379|     '''Generate and return Collatz sequence for n.'''
380|     def inner (arr):
381|         arr[0:0] = yield from gen_collatz_2(n)
382|     cs = []
383|     for n in inner(cs):
384|         print(n)
385|     return cs
386| 
387| cs = collatz_seq(5)
388| print(cs)
389| 
390| #:code::
391| def gen_collatz (n):
392|     '''Collatz sequence generator. (Returns a list!)'''
393|     buf = []
394|     while 1 <= n:
395|         buf.append(n)
396|         yield (len(buf), n)
397|         n = Collatz(n)
398|     return buf
399| 
400| def collatz_stats (accum, start=1, end=100):
401|     '''Collatz length stats wrapper.'''
402|     for n in range(start, end+1):
403|         cs = yield from gen_collatz(n)
404|         accum.append((n,len(cs)))
405| 
406| def demo_collatz_stats (start=1, end=100):
407|     fdata = {}
408|     stats = []
409|     for ix,n in collatz_stats(stats,start,end):
410|         if n not in fdata:
411|             fdata[n] = 0
412|         fdata[n] += 1
413|     freqs = sorted(fdata.items(), key=lambda x:x[0])
414|     return (stats, freqs)
415| 
416| #:code::
417| for level in range(n_levels):
418|     for row in range(n_rows):
419|         for col in range(n_cols):
420|             matrix.do_something(level, row, col)
421| 
422| #:code::
423| def visit_matrix (n_levels, n_rows, n_cols, cb_func):
424|     '''Visit every cell of matrix. Invoke cb_func.'''
425|     for level in range(n_levels):
426|         for row in range(n_rows):
427|             for col in range(n_cols):
428|                 cb_func(level, row, col)
429| 
430| def matrix_do_something (level, row, col):
431|     '''Callback function.'''
432|     matrix.do_something(level, row, col)
433| 
434| # Do something to all matrix cells...
435| visit_matrix(LEVELS,ROWS,COLS, matrix_do_something)
436| 
437| #:code::
438| def gen_matrix (n_levels, n_rows, n_cols):
439|     for level in range(n_levels):
440|         for row in range(n_rows):
441|             for col in range(n_cols):
442|                 yield (level, row, col)
443| 
444| # Do something to all matrix cells...
445| for level,row,col in gen_matrix(LEVELS,ROWS,COLS):
446|     matrix.do_something(level, row, col)
447| 
448| #:code::
449| def gen_columns (curr_level, curr_row, n_cols):
450|     '''Generate column index.'''
451|     for cx in range(n_cols):
452|         yield (curr_level, curr_row, cx)
453| 
454| def gen_rows (curr_level, n_rows, n_cols):
455|     '''Generate row index.'''
456|     for rx in range(n_rows):
457|         yield from gen_columns(curr_level, rx, n_cols)
458| 
459| def gen_levels (n_levels, n_rows, n_cols):
460|     '''Generate level index.'''
461|     for zx in range(n_levels):
462|         yield from gen_rows(zx, n_rows, n_cols)
463| 
464| # Do something to all matrix cells...
465| for level,row,col in gen_levels(LEVELS,ROWS,COLS):
466|     matrix.do_something(level, row, col)
467| 
468| #:code::
469| Letter = ord('a')
470| Digit = ord('0')
471| 
472| def gen_word (px, sx, wmin, wmax):
473|     '''Word generator.'''
474|     w_len = random.randint(wmin, wmax) # length of word
475|     buf = []
476|     for wx in range(w_len):
477|         ch = chr(Letter+randint(0,25))
478|         # Yield indexes, word length, and current char...
479|         signal = yield (px, sx, wx, w_len-1, ch)
480|         if signal is not None:
481|             buf.append(str(signal))
482|             yield len(buf) # Value ignored by .send()
483|             continue
484|         # No signal; just append the character...
485|         buf.append(ch)
486|     # Return the word...
487|     return ''.join(buf)
488| 
489| def gen_sentence (px, smin, smax, wmin, wmax):
490|     '''Sentence generator.'''
491|     s_len = random.randint(smin, smax) # how many words
492|     buf = []
493|     for sx in range(s_len):
494|         word = yield from gen_word(px,sx,wmin,wmax)
495|         buf.append(word)
496|     # Return the sentence...
497|     return ' '.join(buf)
498| 
499| def gen_paragraph (para, pmin,pmax, smin,smax, wmin,wmax):
500|     '''Paragraph generator.'''
501|     punct = ['.', '?', '!']
502|     pbias = [75, 15, 10]
503|     p_len = random.randint(pmin, pmax) # how many sentences
504|     for px in range(p_len):
505|         sent = yield from gen_sentence(px,smin,smax,wmin,wmax)
506|         # End a sentence (usually) with a period...
507|         end = random.choices(punct, k=1, weights=pbias)
508|         para.append('%s%c' % (sent,end[0]))
509| 
510| #:code::
511| paragraph = []
512| gen = gen_paragraph(paragraph, pmin,pmax, smin,smax, wmin,wmax)
513| 
514| # Iterate over the paragraph characters...
515| for px,sx,wx,wlen,ch in gen:
516|     if sx+wx == 0:
517|         gen.send(ch.upper())
518|         continue
519|     if sx == 2:
520|         gen.send(rand_digit())
521|         continue
522| 
523| print()
524| s = ' '.join(paragraph)
525| print(s)
526| print()
527| 
528| #:end:code::
529|