Created
November 29, 2014 20:32
-
-
Save matthieubulte/b78d6555eb1201368594 to your computer and use it in GitHub Desktop.
LazyList
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LazyList(): | |
def __init__(self, iterable): | |
self._list = [] | |
self._iterable = iter(iterable) | |
self._has_thrown = False | |
self._current_index = 0 | |
def __iter__(self): | |
return self | |
def _cached_next(self): | |
if self._current_index >= len(self._list): | |
raise StopIteration() | |
else: | |
index = self._current_index | |
self._current_index += 1 | |
return self._list[index] | |
def _uncached_next(self): | |
_next = self._iterable.next() | |
self._list.append(_next) | |
return _next | |
def next(self): | |
try: | |
return self._cached_next() if self._has_thrown else self._uncached_next() | |
except StopIteration: | |
self._has_thrown = True | |
self._current_index = 0 | |
raise StopIteration() | |
y = LazyList((a*a for a in [1, 2, 3, 4])) | |
# y = LazyList([1, 4, 9, 16]) | |
for x in y: | |
print x**2 | |
for x in y: | |
print x**3 | |
for x in y: | |
print x**4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment