GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — pattern_in_python/iterator_03_python.py at main · FreePhil/pattern_in_python

Expand file tree

/

iterator_03_python.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
370 lines (289 loc) · 9.84 KB
/

iterator_03_python.py

Copy path

File metadata and controls

370 lines (289 loc) · 9.84 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""
ITERATOR PATTERN - Python's Built-in Iterator Protocol
Python has built-in support for the Iterator Pattern using:
- __iter__() method: returns the iterator object
- __next__() method: returns the next item
- StopIteration exception: signals end of iteration
This allows using 'for' loops and other Python iteration features!
"""
# ============================================================
# PYTHONIC ITERATOR - Basic Example
# ============================================================
class Countdown:
"""Iterator that counts down from a number"""
def __init__(self, start):
self.current = start
def __iter__(self):
"""Returns the iterator object (self)"""
return self
def __next__(self):
"""Returns the next item"""
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
# ============================================================
# SEPARATE ITERATOR AND COLLECTION
# ============================================================
class NumberCollection:
"""Collection that stores numbers"""
def __init__(self, numbers):
self._numbers = list(numbers)
def __iter__(self):
"""Returns a new iterator"""
return NumberIterator(self._numbers)
def __len__(self):
return len(self._numbers)
class NumberIterator:
"""Iterator for NumberCollection"""
def __init__(self, numbers):
self._numbers = numbers
self._index = 0
def __iter__(self):
return self
def __next__(self):
if self._index >= len(self._numbers):
raise StopIteration
value = self._numbers[self._index]
self._index += 1
return value
# ============================================================
# CUSTOM ITERATORS WITH FILTERS
# ============================================================
class EvenNumbersIterator:
"""Iterator that only returns even numbers"""
def __init__(self, numbers):
self._numbers = numbers
self._index = 0
def __iter__(self):
return self
def __next__(self):
while self._index < len(self._numbers):
value = self._numbers[self._index]
self._index += 1
if value % 2 == 0:
return value
raise StopIteration
class RangeIterator:
"""Custom range iterator"""
def __init__(self, start, end, step=1):
self.current = start
self.end = end
self.step = step
def __iter__(self):
return self
def __next__(self):
if (self.step > 0 and self.current >= self.end) or \
(self.step < 0 and self.current <= self.end):
raise StopIteration
value = self.current
self.current += self.step
return value
# ============================================================
# INFINITE ITERATOR
# ============================================================
class FibonacciIterator:
"""Infinite Fibonacci sequence iterator"""
def __init__(self):
self.a = 0
self.b = 1
def __iter__(self):
return self
def __next__(self):
result = self.a
self.a, self.b = self.b, self.a + self.b
return result
# ============================================================
# COLLECTION WITH MULTIPLE ITERATION METHODS
# ============================================================
class Playlist:
"""Music playlist with different iteration modes"""
def __init__(self):
self._songs = []
def add_song(self, song):
self._songs.append(song)
def __iter__(self):
"""Default: forward iteration"""
return iter(self._songs)
def reverse_iter(self):
"""Iterate in reverse"""
return reversed(self._songs)
def random_iter(self):
"""Iterate in random order"""
import random
shuffled = self._songs.copy()
random.shuffle(shuffled)
return iter(shuffled)
# ============================================================
# USING GENERATORS (Pythonic way!)
# ============================================================
def countdown_generator(start):
"""Generator function - more Pythonic than iterator class"""
while start > 0:
yield start
start -= 1
def fibonacci_generator(limit=None):
"""Fibonacci generator with optional limit"""
a, b = 0, 1
count = 0
while limit is None or count < limit:
yield a
a, b = b, a + b
count += 1
def even_numbers_generator(numbers):
"""Generator that yields only even numbers"""
for num in numbers:
if num % 2 == 0:
yield num
# ============================================================
# CLIENT CODE
# ============================================================
if __name__ == "__main__":
print("="*60)
print(" Iterator Pattern - Python's Built-in Features")
print("="*60)
# Example 1: Basic iterator
print("\n1. BASIC ITERATOR CLASS")
print("-" * 60)
print("Countdown from 5:")
for num in Countdown(5):
print(f" {num}...", end=" ")
print("Blast off! 🚀\n")
# Example 2: Collection with iterator
print("\n2. COLLECTION WITH ITERATOR")
print("-" * 60)
numbers = NumberCollection([1, 2, 3, 4, 5])
print(f"Collection has {len(numbers)} numbers:")
for num in numbers:
print(f" {num}", end=" ")
print()
# Multiple iterations
print("\nMultiple iterations (creates new iterator each time):")
iter1 = iter(numbers)
iter2 = iter(numbers)
print(f" Iterator 1 - first: {next(iter1)}, second: {next(iter1)}")
print(f" Iterator 2 - first: {next(iter2)}, second: {next(iter2)}")
# Example 3: Filtered iterator
print("\n\n3. FILTERED ITERATOR (Even numbers only)")
print("-" * 60)
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(f"Original: {data}")
print("Even numbers:", end=" ")
for num in EvenNumbersIterator(data):
print(num, end=" ")
print()
# Example 4: Custom range
print("\n\n4. CUSTOM RANGE ITERATOR")
print("-" * 60)
print("Range(0, 10, 2):", end=" ")
for num in RangeIterator(0, 10, 2):
print(num, end=" ")
print()
print("Range(10, 0, -1):", end=" ")
for num in RangeIterator(10, 0, -1):
print(num, end=" ")
print()
# Example 5: Infinite iterator (with limit)
print("\n\n5. INFINITE ITERATOR (Fibonacci)")
print("-" * 60)
print("First 10 Fibonacci numbers:")
fib = FibonacciIterator()
for i in range(10):
print(f" F({i}) = {next(fib)}")
# Example 6: Multiple iteration modes
print("\n\n6. MULTIPLE ITERATION MODES (Playlist)")
print("-" * 60)
playlist = Playlist()
for song in ["Song A", "Song B", "Song C", "Song D"]:
playlist.add_song(song)
print("Forward:")
print(" " + " → ".join(playlist))
print("\nReverse:")
print(" " + " → ".join(playlist.reverse_iter()))
print("\nRandom (shuffle):")
print(" " + " → ".join(playlist.random_iter()))
# Example 7: Generators (Pythonic way!)
print("\n\n7. GENERATORS (More Pythonic)")
print("-" * 60)
print("Countdown generator:")
for num in countdown_generator(5):
print(f" {num}...", end=" ")
print("Done!")
print("\n\nFibonacci generator (first 10):")
for num in fibonacci_generator(10):
print(f" {num}", end=" ")
print()
print("\n\nEven numbers generator:")
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(even_numbers_generator(numbers))
print(f" {evens}")
# Example 8: Built-in Python iteration tools
print("\n\n8. PYTHON'S BUILT-IN ITERATION TOOLS")
print("-" * 60)
data = [1, 2, 3, 4, 5]
print(f"Original: {data}")
print(f"Reversed: {list(reversed(data))}")
print(f"Enumerate: {list(enumerate(data))}")
print(f"Zip: {list(zip(data, ['a', 'b', 'c', 'd', 'e']))}")
# Example 9: Iterator protocol in action
print("\n\n9. ITERATOR PROTOCOL IN ACTION")
print("-" * 60)
print("Manual iteration (what 'for' loop does internally):")
collection = NumberCollection([10, 20, 30])
iterator = iter(collection) # Calls __iter__()
try:
while True:
item = next(iterator) # Calls __next__()
print(f" Got: {item}")
except StopIteration:
print(" Iteration complete!")
print("\n" + "="*60)
print("🔑 PYTHON'S ITERATOR FEATURES:")
print("="*60)
print("""
1. PROTOCOL METHODS:
__iter__(): Returns iterator object
__next__(): Returns next item or raises StopIteration
2. FOR LOOP SUPPORT:
for item in collection:
# Automatically uses __iter__() and __next__()
3. BUILT-IN FUNCTIONS:
iter() - Get iterator from iterable
next() - Get next item from iterator
reversed() - Reverse iteration
enumerate() - Add index to iteration
zip() - Parallel iteration
4. GENERATORS (Recommended):
def my_gen():
yield item
# Simpler than creating iterator classes!
5. COMPREHENSIONS:
[x for x in collection] # List comprehension
(x for x in collection) # Generator expression
{x for x in collection} # Set comprehension
{k:v for k,v in items} # Dict comprehension
""")
print("\n" + "="*60)
print("💡 BEST PRACTICE:")
print("="*60)
print("""
In Python, prefer GENERATORS over ITERATOR CLASSES:
❌ Old way (verbose):
class MyIterator:
def __init__(self, data):
self.data = data
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.data):
raise StopIteration
result = self.data[self.index]
self.index += 1
return result
✅ New way (Pythonic):
def my_generator(data):
for item in data:
yield item
Generators are simpler, more readable, and memory-efficient!
""")
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.