Last active
April 11, 2019 20:59
-
-
Save chisler/b1188c176e7ea09aefa74fae0487183f to your computer and use it in GitHub Desktop.
Second One
This file contains 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
""" | |
Create an iterator that yields elements of nested list. | |
""" | |
class FlatIterator: | |
def __init__(self, data): | |
self.stack = [iter(data)] | |
def __iter__(self): | |
return self | |
def __next__(self): | |
if not self.stack: | |
raise StopIteration | |
current = self.stack.pop() | |
try: | |
element = next(current) | |
self.stack.append(current) | |
if isinstance(element, list): | |
self.stack.append(iter(element)) | |
# If we've found a list, | |
# we need to iterate it instead | |
return next(self) | |
else: | |
return element | |
except StopIteration: | |
# If current iterator has finished | |
# We need to try next one | |
return next(self) | |
a = [ | |
[1, 2, 3], | |
[4, [5], 6], | |
[], | |
[[7]] | |
] | |
flat = FlatIterator(a) | |
assert [i for i in flat] == list(range(1, 8)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment