-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01-iterator-pattern.py
More file actions
1231 lines (915 loc) · 39 KB
/
01-iterator-pattern.py
File metadata and controls
1231 lines (915 loc) · 39 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
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Question: Implement the Iterator pattern to provide sequential access to elements without exposing structure.
Create a playlist system where songs can be iterated in different orders
(sequential, shuffle, repeat) without exposing the internal collection structure.
Requirements:
1. Create Iterator interface with has_next() and next() methods
2. Implement concrete iterators (Sequential, Shuffle, Repeat)
3. Create Aggregate interface with create_iterator() method
4. Implement Playlist class that creates different iterators
5. Demonstrate different iteration strategies
6. Show how Python's iterator protocol can be used
Example usage:
playlist = Playlist()
playlist.add_song("Song 1")
playlist.add_song("Song 2")
iterator = playlist.create_iterator("shuffle")
while iterator.has_next():
print(iterator.next())
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
# Try to implement your solution here:
# (Write your code below this line)
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Import modules and create the Song class
# ===============================================================================
# Explanation:
# The Iterator pattern starts with the objects we want to iterate over.
# We'll create a Song class to represent individual songs in our playlist.
from abc import ABC, abstractmethod
from typing import List, Optional
import random
class Song:
"""Represents a song in the playlist."""
def __init__(self, title: str, artist: str = "Unknown", duration: int = 180):
self.title = title
self.artist = artist
self.duration = duration # duration in seconds
def __str__(self):
"""String representation of the song."""
minutes = self.duration // 60
seconds = self.duration % 60
return f"{self.title} by {self.artist} ({minutes}:{seconds:02d})"
def __repr__(self):
return f"Song('{self.title}', '{self.artist}', {self.duration})"
# What we accomplished in this step:
# - Created the Song class with title, artist, and duration
# - Added string representation for easy display
# - This will be the element type our iterators will work with
# Step 2: Create the abstract iterator interface
# ===============================================================================
# Explanation:
# The Iterator interface defines the contract for all concrete iterators.
# It provides methods to check if there are more elements and to get the next element.
from abc import ABC, abstractmethod
from typing import List, Optional
import random
class Song:
"""Represents a song in the playlist."""
def __init__(self, title: str, artist: str = "Unknown", duration: int = 180):
self.title = title
self.artist = artist
self.duration = duration # duration in seconds
def __str__(self):
"""String representation of the song."""
minutes = self.duration // 60
seconds = self.duration % 60
return f"{self.title} by {self.artist} ({minutes}:{seconds:02d})"
def __repr__(self):
return f"Song('{self.title}', '{self.artist}', {self.duration})"
class Iterator(ABC):
"""Abstract iterator interface."""
@abstractmethod
def has_next(self) -> bool:
"""Check if there are more elements to iterate over."""
pass
@abstractmethod
def next(self) -> Song:
"""Get the next element in the iteration."""
pass
@abstractmethod
def reset(self):
"""Reset the iterator to the beginning."""
pass
# What we accomplished in this step:
# - Created abstract Iterator interface with essential methods
# - has_next() checks if more elements are available
# - next() returns the next element in sequence
# - reset() allows restarting iteration from the beginning
# Step 3: Create concrete sequential iterator
# ===============================================================================
# Explanation:
# The SequentialIterator iterates through songs in their original order.
# It maintains a current position and moves forward one song at a time.
from abc import ABC, abstractmethod
from typing import List, Optional
import random
class Song:
"""Represents a song in the playlist."""
def __init__(self, title: str, artist: str = "Unknown", duration: int = 180):
self.title = title
self.artist = artist
self.duration = duration # duration in seconds
def __str__(self):
"""String representation of the song."""
minutes = self.duration // 60
seconds = self.duration % 60
return f"{self.title} by {self.artist} ({minutes}:{seconds:02d})"
def __repr__(self):
return f"Song('{self.title}', '{self.artist}', {self.duration})"
class Iterator(ABC):
"""Abstract iterator interface."""
@abstractmethod
def has_next(self) -> bool:
"""Check if there are more elements to iterate over."""
pass
@abstractmethod
def next(self) -> Song:
"""Get the next element in the iteration."""
pass
@abstractmethod
def reset(self):
"""Reset the iterator to the beginning."""
pass
class SequentialIterator(Iterator):
"""Iterator that goes through songs in sequential order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.songs)
def next(self) -> Song:
"""Get the next song in sequence."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song = self.songs[self.current_index]
self.current_index += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
# What we accomplished in this step:
# - Created SequentialIterator that iterates in original order
# - Maintains current_index to track position
# - Implements all abstract methods from Iterator interface
# - Raises StopIteration when no more elements available
# Step 4: Create concrete shuffle iterator
# ===============================================================================
# Explanation:
# The ShuffleIterator randomizes the order of songs but still visits each song exactly once.
# It creates a shuffled copy of the song indices to maintain randomness.
from abc import ABC, abstractmethod
from typing import List, Optional
import random
class Song:
"""Represents a song in the playlist."""
def __init__(self, title: str, artist: str = "Unknown", duration: int = 180):
self.title = title
self.artist = artist
self.duration = duration # duration in seconds
def __str__(self):
"""String representation of the song."""
minutes = self.duration // 60
seconds = self.duration % 60
return f"{self.title} by {self.artist} ({minutes}:{seconds:02d})"
def __repr__(self):
return f"Song('{self.title}', '{self.artist}', {self.duration})"
class Iterator(ABC):
"""Abstract iterator interface."""
@abstractmethod
def has_next(self) -> bool:
"""Check if there are more elements to iterate over."""
pass
@abstractmethod
def next(self) -> Song:
"""Get the next element in the iteration."""
pass
@abstractmethod
def reset(self):
"""Reset the iterator to the beginning."""
pass
class SequentialIterator(Iterator):
"""Iterator that goes through songs in sequential order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.songs)
def next(self) -> Song:
"""Get the next song in sequence."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song = self.songs[self.current_index]
self.current_index += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
class ShuffleIterator(Iterator):
"""Iterator that goes through songs in random order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.shuffled_indices = list(range(len(songs)))
random.shuffle(self.shuffled_indices)
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.shuffled_indices)
def next(self) -> Song:
"""Get the next song in shuffled order."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song_index = self.shuffled_indices[self.current_index]
song = self.songs[song_index]
self.current_index += 1
return song
def reset(self):
"""Reset and reshuffle the playlist."""
random.shuffle(self.shuffled_indices)
self.current_index = 0
# What we accomplished in this step:
# - Created ShuffleIterator that randomizes song order
# - Uses shuffled_indices to maintain random but complete iteration
# - Reset method reshuffles for different random order each time
# - Still visits each song exactly once per iteration cycle
# Step 5: Create concrete repeat iterator
# ===============================================================================
# Explanation:
# The RepeatIterator cycles through songs infinitely, starting over when it reaches the end.
# It can be configured to repeat a certain number of times or infinitely.
from abc import ABC, abstractmethod
from typing import List, Optional
import random
class Song:
"""Represents a song in the playlist."""
def __init__(self, title: str, artist: str = "Unknown", duration: int = 180):
self.title = title
self.artist = artist
self.duration = duration # duration in seconds
def __str__(self):
"""String representation of the song."""
minutes = self.duration // 60
seconds = self.duration % 60
return f"{self.title} by {self.artist} ({minutes}:{seconds:02d})"
def __repr__(self):
return f"Song('{self.title}', '{self.artist}', {self.duration})"
class Iterator(ABC):
"""Abstract iterator interface."""
@abstractmethod
def has_next(self) -> bool:
"""Check if there are more elements to iterate over."""
pass
@abstractmethod
def next(self) -> Song:
"""Get the next element in the iteration."""
pass
@abstractmethod
def reset(self):
"""Reset the iterator to the beginning."""
pass
class SequentialIterator(Iterator):
"""Iterator that goes through songs in sequential order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.songs)
def next(self) -> Song:
"""Get the next song in sequence."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song = self.songs[self.current_index]
self.current_index += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
class ShuffleIterator(Iterator):
"""Iterator that goes through songs in random order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.shuffled_indices = list(range(len(songs)))
random.shuffle(self.shuffled_indices)
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.shuffled_indices)
def next(self) -> Song:
"""Get the next song in shuffled order."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song_index = self.shuffled_indices[self.current_index]
song = self.songs[song_index]
self.current_index += 1
return song
def reset(self):
"""Reset and reshuffle the playlist."""
random.shuffle(self.shuffled_indices)
self.current_index = 0
class RepeatIterator(Iterator):
"""Iterator that repeats the playlist a specified number of times or infinitely."""
def __init__(self, songs: List[Song], repeat_count: Optional[int] = None):
self.songs = songs
self.repeat_count = repeat_count # None means infinite repeat
self.current_index = 0
self.cycles_completed = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
if not self.songs:
return False
# If repeat_count is None, always has next (infinite)
if self.repeat_count is None:
return True
# Check if we've completed all requested cycles
return self.cycles_completed < self.repeat_count
def next(self) -> Song:
"""Get the next song, cycling through the playlist."""
if not self.has_next():
raise StopIteration("Playlist repetition completed")
song = self.songs[self.current_index]
self.current_index += 1
# Check if we've reached the end of the playlist
if self.current_index >= len(self.songs):
self.current_index = 0
self.cycles_completed += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
self.cycles_completed = 0
# What we accomplished in this step:
# - Created RepeatIterator that cycles through songs multiple times
# - Supports both finite repeat count and infinite repetition
# - Tracks cycles_completed to know when to stop
# - Automatically wraps around to beginning when reaching end
# Step 6: Create aggregate interface and Playlist class
# ===============================================================================
# Explanation:
# The Aggregate interface defines how to create iterators. The Playlist class
# implements this interface and can create different types of iterators for the same data.
from abc import ABC, abstractmethod
from typing import List, Optional
import random
class Song:
"""Represents a song in the playlist."""
def __init__(self, title: str, artist: str = "Unknown", duration: int = 180):
self.title = title
self.artist = artist
self.duration = duration # duration in seconds
def __str__(self):
"""String representation of the song."""
minutes = self.duration // 60
seconds = self.duration % 60
return f"{self.title} by {self.artist} ({minutes}:{seconds:02d})"
def __repr__(self):
return f"Song('{self.title}', '{self.artist}', {self.duration})"
class Iterator(ABC):
"""Abstract iterator interface."""
@abstractmethod
def has_next(self) -> bool:
"""Check if there are more elements to iterate over."""
pass
@abstractmethod
def next(self) -> Song:
"""Get the next element in the iteration."""
pass
@abstractmethod
def reset(self):
"""Reset the iterator to the beginning."""
pass
class SequentialIterator(Iterator):
"""Iterator that goes through songs in sequential order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.songs)
def next(self) -> Song:
"""Get the next song in sequence."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song = self.songs[self.current_index]
self.current_index += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
class ShuffleIterator(Iterator):
"""Iterator that goes through songs in random order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.shuffled_indices = list(range(len(songs)))
random.shuffle(self.shuffled_indices)
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.shuffled_indices)
def next(self) -> Song:
"""Get the next song in shuffled order."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song_index = self.shuffled_indices[self.current_index]
song = self.songs[song_index]
self.current_index += 1
return song
def reset(self):
"""Reset and reshuffle the playlist."""
random.shuffle(self.shuffled_indices)
self.current_index = 0
class RepeatIterator(Iterator):
"""Iterator that repeats the playlist a specified number of times or infinitely."""
def __init__(self, songs: List[Song], repeat_count: Optional[int] = None):
self.songs = songs
self.repeat_count = repeat_count # None means infinite repeat
self.current_index = 0
self.cycles_completed = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
if not self.songs:
return False
# If repeat_count is None, always has next (infinite)
if self.repeat_count is None:
return True
# Check if we've completed all requested cycles
return self.cycles_completed < self.repeat_count
def next(self) -> Song:
"""Get the next song, cycling through the playlist."""
if not self.has_next():
raise StopIteration("Playlist repetition completed")
song = self.songs[self.current_index]
self.current_index += 1
# Check if we've reached the end of the playlist
if self.current_index >= len(self.songs):
self.current_index = 0
self.cycles_completed += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
self.cycles_completed = 0
class Aggregate(ABC):
"""Abstract aggregate interface for creating iterators."""
@abstractmethod
def create_iterator(self, iterator_type: str = "sequential") -> Iterator:
"""Create an iterator for the collection."""
pass
class Playlist(Aggregate):
"""Playlist that can create different types of iterators."""
def __init__(self, name: str = "My Playlist"):
self.name = name
self.songs: List[Song] = []
def add_song(self, song: Song):
"""Add a song to the playlist."""
self.songs.append(song)
def remove_song(self, song: Song):
"""Remove a song from the playlist."""
if song in self.songs:
self.songs.remove(song)
def get_song_count(self) -> int:
"""Get the number of songs in the playlist."""
return len(self.songs)
def create_iterator(self, iterator_type: str = "sequential", **kwargs) -> Iterator:
"""Create an iterator based on the specified type."""
if iterator_type.lower() == "sequential":
return SequentialIterator(self.songs.copy())
elif iterator_type.lower() == "shuffle":
return ShuffleIterator(self.songs.copy())
elif iterator_type.lower() == "repeat":
repeat_count = kwargs.get("repeat_count", None)
return RepeatIterator(self.songs.copy(), repeat_count)
else:
raise ValueError(f"Unknown iterator type: {iterator_type}")
def __str__(self):
"""String representation of the playlist."""
return f"Playlist '{self.name}' with {len(self.songs)} songs"
# What we accomplished in this step:
# - Created Aggregate interface for iterator creation
# - Implemented Playlist class that manages songs and creates iterators
# - Added methods to add/remove songs and get song count
# - Factory method create_iterator() supports different iterator types
# - Uses copy() to prevent external modification of internal song list
# Step 7: Add Python's iterator protocol support
# ===============================================================================
# Explanation:
# Python has built-in iterator protocol using __iter__() and __next__() methods.
# We'll create a Pythonic iterator that works with for loops and other Python constructs.
from abc import ABC, abstractmethod
from typing import List, Optional
import random
class Song:
"""Represents a song in the playlist."""
def __init__(self, title: str, artist: str = "Unknown", duration: int = 180):
self.title = title
self.artist = artist
self.duration = duration # duration in seconds
def __str__(self):
"""String representation of the song."""
minutes = self.duration // 60
seconds = self.duration % 60
return f"{self.title} by {self.artist} ({minutes}:{seconds:02d})"
def __repr__(self):
return f"Song('{self.title}', '{self.artist}', {self.duration})"
class Iterator(ABC):
"""Abstract iterator interface."""
@abstractmethod
def has_next(self) -> bool:
"""Check if there are more elements to iterate over."""
pass
@abstractmethod
def next(self) -> Song:
"""Get the next element in the iteration."""
pass
@abstractmethod
def reset(self):
"""Reset the iterator to the beginning."""
pass
class SequentialIterator(Iterator):
"""Iterator that goes through songs in sequential order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.songs)
def next(self) -> Song:
"""Get the next song in sequence."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song = self.songs[self.current_index]
self.current_index += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
class ShuffleIterator(Iterator):
"""Iterator that goes through songs in random order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.shuffled_indices = list(range(len(songs)))
random.shuffle(self.shuffled_indices)
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.shuffled_indices)
def next(self) -> Song:
"""Get the next song in shuffled order."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song_index = self.shuffled_indices[self.current_index]
song = self.songs[song_index]
self.current_index += 1
return song
def reset(self):
"""Reset and reshuffle the playlist."""
random.shuffle(self.shuffled_indices)
self.current_index = 0
class RepeatIterator(Iterator):
"""Iterator that repeats the playlist a specified number of times or infinitely."""
def __init__(self, songs: List[Song], repeat_count: Optional[int] = None):
self.songs = songs
self.repeat_count = repeat_count # None means infinite repeat
self.current_index = 0
self.cycles_completed = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
if not self.songs:
return False
# If repeat_count is None, always has next (infinite)
if self.repeat_count is None:
return True
# Check if we've completed all requested cycles
return self.cycles_completed < self.repeat_count
def next(self) -> Song:
"""Get the next song, cycling through the playlist."""
if not self.has_next():
raise StopIteration("Playlist repetition completed")
song = self.songs[self.current_index]
self.current_index += 1
# Check if we've reached the end of the playlist
if self.current_index >= len(self.songs):
self.current_index = 0
self.cycles_completed += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
self.cycles_completed = 0
class Aggregate(ABC):
"""Abstract aggregate interface for creating iterators."""
@abstractmethod
def create_iterator(self, iterator_type: str = "sequential") -> Iterator:
"""Create an iterator for the collection."""
pass
class Playlist(Aggregate):
"""Playlist that can create different types of iterators."""
def __init__(self, name: str = "My Playlist"):
self.name = name
self.songs: List[Song] = []
def add_song(self, song: Song):
"""Add a song to the playlist."""
self.songs.append(song)
def remove_song(self, song: Song):
"""Remove a song from the playlist."""
if song in self.songs:
self.songs.remove(song)
def get_song_count(self) -> int:
"""Get the number of songs in the playlist."""
return len(self.songs)
def create_iterator(self, iterator_type: str = "sequential", **kwargs) -> Iterator:
"""Create an iterator based on the specified type."""
if iterator_type.lower() == "sequential":
return SequentialIterator(self.songs.copy())
elif iterator_type.lower() == "shuffle":
return ShuffleIterator(self.songs.copy())
elif iterator_type.lower() == "repeat":
repeat_count = kwargs.get("repeat_count", None)
return RepeatIterator(self.songs.copy(), repeat_count)
else:
raise ValueError(f"Unknown iterator type: {iterator_type}")
def __str__(self):
"""String representation of the playlist."""
return f"Playlist '{self.name}' with {len(self.songs)} songs"
class PythonicPlaylistIterator:
"""Python-style iterator that works with for loops and built-in functions."""
def __init__(self, iterator: Iterator):
self.iterator = iterator
def __iter__(self):
"""Return self as the iterator object."""
return self
def __next__(self):
"""Get the next item using Python's iterator protocol."""
if self.iterator.has_next():
return self.iterator.next()
else:
raise StopIteration
class PythonicPlaylist(Playlist):
"""Enhanced playlist that supports Python's iterator protocol."""
def __iter__(self):
"""Return a Python-style iterator for the playlist."""
return PythonicPlaylistIterator(self.create_iterator("sequential"))
def iter_shuffle(self):
"""Return a shuffled Python-style iterator."""
return PythonicPlaylistIterator(self.create_iterator("shuffle"))
def iter_repeat(self, repeat_count: Optional[int] = None):
"""Return a repeating Python-style iterator."""
return PythonicPlaylistIterator(self.create_iterator("repeat", repeat_count=repeat_count))
# What we accomplished in this step:
# - Created PythonicPlaylistIterator that implements __iter__ and __next__
# - Enhanced PythonicPlaylist to work with Python's for loops
# - Added convenience methods for different iteration types
# - Now supports: for song in playlist, list(playlist), etc.
# Step 8: Test the complete implementation
# ===============================================================================
# Explanation:
# Let's test our Iterator pattern implementation with different iteration strategies
# and demonstrate both custom iterators and Python's built-in iterator protocol.
from abc import ABC, abstractmethod
from typing import List, Optional
import random
class Song:
"""Represents a song in the playlist."""
def __init__(self, title: str, artist: str = "Unknown", duration: int = 180):
self.title = title
self.artist = artist
self.duration = duration # duration in seconds
def __str__(self):
"""String representation of the song."""
minutes = self.duration // 60
seconds = self.duration % 60
return f"{self.title} by {self.artist} ({minutes}:{seconds:02d})"
def __repr__(self):
return f"Song('{self.title}', '{self.artist}', {self.duration})"
class Iterator(ABC):
"""Abstract iterator interface."""
@abstractmethod
def has_next(self) -> bool:
"""Check if there are more elements to iterate over."""
pass
@abstractmethod
def next(self) -> Song:
"""Get the next element in the iteration."""
pass
@abstractmethod
def reset(self):
"""Reset the iterator to the beginning."""
pass
class SequentialIterator(Iterator):
"""Iterator that goes through songs in sequential order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""
return self.current_index < len(self.songs)
def next(self) -> Song:
"""Get the next song in sequence."""
if not self.has_next():
raise StopIteration("No more songs in the playlist")
song = self.songs[self.current_index]
self.current_index += 1
return song
def reset(self):
"""Reset to the beginning of the playlist."""
self.current_index = 0
class ShuffleIterator(Iterator):
"""Iterator that goes through songs in random order."""
def __init__(self, songs: List[Song]):
self.songs = songs
self.shuffled_indices = list(range(len(songs)))
random.shuffle(self.shuffled_indices)
self.current_index = 0
def has_next(self) -> bool:
"""Check if there are more songs to play."""