-
Notifications
You must be signed in to change notification settings - Fork 0
/
infinity_iterator.py
43 lines (28 loc) · 939 Bytes
/
infinity_iterator.py
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
# Task - create infinity iterator
# Solution 1
from typing import Any, Iterable, Iterator
class CyclicIterator:
_collection: Iterable
_iterator: Iterator
def __init__(self, collection: Iterable) -> None:
self._collection = collection
self._iterator = iter(self._collection)
def __iter__(self) -> Iterator:
return self
def __next__(self) -> Any:
try:
return next(self._iterator)
except StopIteration:
self._iterator = iter(self._collection)
return next(self._iterator)
# Solution 2
from itertools import cycle
from typing import Any, Iterable, Iterator
class CyclicIterator:
_iterator: Iterator
def __init__(self, collection: Iterable) -> None:
self._iterator = cycle(collection)
def __iter__(self) -> Iterator:
return self
def __next__(self) -> Any:
return next(self._iterator)