-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerators.py
More file actions
279 lines (208 loc) · 6.58 KB
/
Copy pathgenerators.py
File metadata and controls
279 lines (208 loc) · 6.58 KB
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
"""
Module: generators.py
Topic: Generators in Python
Level: Advanced
This file teaches you about:
- Generator functions and yield
- Generator expressions
- yield from
- Generator pipelines
- Memory efficiency
"""
# =============================================================================
# SECTION 1: GENERATOR FUNCTIONS
# =============================================================================
print("=" * 60)
print("GENERATOR FUNCTIONS")
print("=" * 60)
def count_up_to(n):
"""A simple generator that counts up to n."""
count = 1
while count <= n:
yield count
count += 1
# Using the generator
print("count_up_to(5):")
for num in count_up_to(5):
print(f" {num}")
# Generators return an iterator
counter = count_up_to(3)
print(f"\nType: {type(counter)}")
print(f"next(): {next(counter)}")
print(f"next(): {next(counter)}")
print(f"next(): {next(counter)}")
# next(counter) # Would raise StopIteration
# =============================================================================
# SECTION 2: GENERATOR EXPRESSIONS
# =============================================================================
print("\n" + "=" * 60)
print("GENERATOR EXPRESSIONS")
print("=" * 60)
# List comprehension (creates entire list in memory)
squares_list = [x**2 for x in range(10)]
print(f"List: {squares_list}")
# Generator expression (lazy evaluation)
squares_gen = (x**2 for x in range(10))
print(f"Generator: {squares_gen}")
print(f"Values: {list(squares_gen)}")
# Memory efficiency demo
import sys
big_list = [x for x in range(10000)]
big_gen = (x for x in range(10000))
print(f"\nMemory comparison:")
print(f" List size: {sys.getsizeof(big_list)} bytes")
print(f" Generator size: {sys.getsizeof(big_gen)} bytes")
# =============================================================================
# SECTION 3: YIELD FROM
# =============================================================================
print("\n" + "=" * 60)
print("YIELD FROM")
print("=" * 60)
def flatten(nested):
"""Flatten a nested list using yield from."""
for item in nested:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
nested = [1, [2, 3], [4, [5, 6]], 7]
print(f"Nested: {nested}")
print(f"Flattened: {list(flatten(nested))}")
# yield from with generators
def chain_generators(*gens):
"""Chain multiple generators together."""
for gen in gens:
yield from gen
gen1 = (x for x in range(3))
gen2 = (x for x in range(3, 6))
print(f"\nChained: {list(chain_generators(gen1, gen2))}")
# =============================================================================
# SECTION 4: GENERATOR PIPEELINES
# =============================================================================
print("\n" + "=" * 60)
print("GENERATOR PIPELINES")
print("=" * 60)
def read_lines(text):
"""Yield lines from text."""
for line in text.split('\n'):
yield line.strip()
def filter_comments(lines):
"""Filter out comment lines."""
for line in lines:
if line and not line.startswith('#'):
yield line
def to_uppercase(lines):
"""Convert lines to uppercase."""
for line in lines:
yield line.upper()
# Pipeline
text = """
# Configuration file
name: alice
age: 25
# End of config
"""
pipeline = to_uppercase(filter_comments(read_lines(text)))
print("Pipeline result:")
for line in pipeline:
print(f" {line}")
# =============================================================================
# SECTION 5: INFINITE GENERATORS
# =============================================================================
print("\n" + "=" * 60)
print("INFINITE GENERATORS")
print("=" * 60)
from itertools import islice
def fibonacci():
"""Generate infinite Fibonacci sequence."""
a, b = 0, 1
while True:
yield a
a, b = b, a + b
def primes():
"""Generate infinite prime numbers."""
num = 2
while True:
if all(num % i != 0 for i in range(2, int(num ** 0.5) + 1)):
yield num
num += 1
# Using islice to limit output
print("First 10 Fibonacci numbers:")
print(f" {list(islice(fibonacci(), 10))}")
print("\nFirst 10 prime numbers:")
print(f" {list(islice(primes(), 10))}")
# =============================================================================
# SECTION 6: COROUTINE-STYLE GENERATORS
# =============================================================================
print("\n" + "=" * 60)
print("COROUTINE-STYLE GENERATORS (send)")
print("=" * 60)
def accumulator():
"""A generator that accumulates sent values."""
total = 0
while True:
value = yield total
if value is None:
break
total += value
acc = accumulator()
next(acc) # Prime the generator
print("Accumulator:")
print(f" Send 10: {acc.send(10)}")
print(f" Send 20: {acc.send(20)}")
print(f" Send 30: {acc.send(30)}")
acc.close()
# =============================================================================
# SECTION 7: PRACTICAL EXAMPLES
# =============================================================================
print("\n" + "=" * 60)
print("PRACTICAL EXAMPLES")
print("=" * 60)
def chunked(iterable, size):
"""Yield chunks of specified size."""
chunk = []
for item in iterable:
chunk.append(item)
if len(chunk) == size:
yield chunk
chunk = []
if chunk:
yield chunk
print("Chunked [1-10] into 3s:")
for chunk in chunked(range(1, 11), 3):
print(f" {chunk}")
def sliding_window(iterable, size):
"""Yield sliding windows."""
from collections import deque
window = deque(maxlen=size)
for item in iterable:
window.append(item)
if len(window) == size:
yield tuple(window)
print("\nSliding window of size 3:")
for window in sliding_window([1, 2, 3, 4, 5], 3):
print(f" {window}")
def file_lines(filename):
"""Yield lines from a file (example)."""
# In real use:
# with open(filename) as f:
# for line in f:
# yield line.strip()
pass
def batch_processor(items, process_func, batch_size=100):
"""Process items in batches."""
batch = []
for item in items:
batch.append(process_func(item))
if len(batch) >= batch_size:
yield batch
batch = []
if batch:
yield batch
# =============================================================================
# MAIN EXECUTION
# =============================================================================
if __name__ == "__main__":
print("\n" + "=" * 60)
print("✅ You've learned about generators!")
print("=" * 60)