-
Notifications
You must be signed in to change notification settings - Fork 7k
Expand file tree
/
Copy pathiterator.py
More file actions
38 lines (27 loc) · 1.02 KB
/
iterator.py
File metadata and controls
38 lines (27 loc) · 1.02 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
from __future__ import annotations
from typing import Generic, Iterable, Iterator, List, TypeVar
T = TypeVar("T")
class AlphabeticalOrderIterator(Iterator[T], Generic[T]):
def __init__(self, collection: List[T]) -> None:
self._collection = collection
self._position = 0
def __next__(self) -> T:
try:
value = self._collection[self._position]
self._position += 1
except IndexError:
raise StopIteration()
return value
class WordsCollection(Iterable[T], Generic[T]):
def __init__(self, collection: List[T] = []) -> None:
self._collection = collection
def __iter__(self) -> AlphabeticalOrderIterator[T]:
return AlphabeticalOrderIterator(self._collection)
def add_item(self, item: T) -> None:
self._collection.append(item)
if __name__ == "__main__":
collection = WordsCollection[str]()
collection.add_item("First")
collection.add_item("Second")
collection.add_item("Third")
print("\n".join(collection))