Created
February 17, 2016 09:34
-
-
Save ojengwa/862831cdd23b62e84dd6 to your computer and use it in GitHub Desktop.
Will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
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
import itertools | |
def flatten(iterable): | |
iterable = iter(iterable) | |
while True: | |
try: | |
item = iterable.next() | |
except StopIteration as e: | |
break | |
try: | |
data = iter(item) | |
iterable = itertools.chain(data, iterable) | |
except: | |
yield item | |
# To use: | |
# array = [[1,2,[3, [5]]],[4]] | |
# merged = flatten(array) | |
# next(merged) will lazily yeild the next element in the sequence |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment