Skip to content

Commit 6d32ad9

Browse files
committed
Updated examples.
1 parent e1bc998 commit 6d32ad9

File tree

2 files changed

+26
-16
lines changed

2 files changed

+26
-16
lines changed

src/Iterator/Conceptual/Output.txt

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
Straight traversal:
2-
First
3-
Second
4-
Third
2+
A
3+
B
4+
C
55

66
Reverse traversal:
7-
Third
8-
Second
9-
First
7+
C
8+
B
9+
A

src/Iterator/Conceptual/main.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
объектов, не раскрывая их внутреннего представления.
1111
"""
1212

13-
1413
from __future__ import annotations
1514
from collections.abc import Iterable, Iterator
1615
from typing import Any
@@ -58,9 +57,22 @@ class AlphabeticalOrderIterator(Iterator):
5857
def __init__(self, collection: WordsCollection, reverse: bool = False) -> None:
5958
self._collection = collection
6059
self._reverse = reverse
61-
self._position = -1 if reverse else 0
60+
self._sorted_items = None # Will be set on first __next__ call
61+
self._position = 0
6262

6363
def __next__(self) -> Any:
64+
"""
65+
EN: Optimization: sorting happens only when the first items is actually
66+
requested.
67+
68+
RU: Оптимизация: сортировка происходит только тогда, когда первый элемент
69+
впервые запрашивается.
70+
"""
71+
if self._sorted_items is None:
72+
self._sorted_items = sorted(self._collection._collection)
73+
if self._reverse:
74+
self._sorted_items = list(reversed(self._sorted_items))
75+
6476
"""
6577
EN: The __next__() method must return the next item in the sequence. On
6678
reaching the end, and in subsequent calls, it must raise StopIteration.
@@ -69,12 +81,10 @@ def __next__(self) -> Any:
6981
последовательности. При достижении конца коллекции и в последующих
7082
вызовах должно вызываться исключение StopIteration.
7183
"""
72-
try:
73-
value = self._collection[self._position]
74-
self._position += -1 if self._reverse else 1
75-
except IndexError:
84+
if self._position >= len(self._sorted_items):
7685
raise StopIteration()
77-
86+
value = self._sorted_items[self._position]
87+
self._position += 1
7888
return value
7989

8090

@@ -120,9 +130,9 @@ def add_item(self, item: Any) -> None:
120130
# классах Коллекций, в зависимости от уровня косвенности, который вы хотите
121131
# сохранить в своей программе.
122132
collection = WordsCollection()
123-
collection.add_item("First")
124-
collection.add_item("Second")
125-
collection.add_item("Third")
133+
collection.add_item("B")
134+
collection.add_item("A")
135+
collection.add_item("C")
126136

127137
print("Straight traversal:")
128138
print("\n".join(collection))

0 commit comments

Comments
 (0)