Last active
July 12, 2017 14:36
-
-
Save dppereyra/178605e04b330547eda5d96dfc1722cb to your computer and use it in GitHub Desktop.
Flatten List
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
def flatten1(list_): | |
'''Flatten nested list of integers into a single list. | |
Args: | |
list_ (list): list to be flattened | |
Returns: | |
Iterable[int]: the flattened list. | |
''' | |
result = [] | |
for item in list_: | |
if isinstance(item, list): | |
result = result + flatten1(item) | |
else: | |
result.append(item) | |
return result | |
def flatten2(list_): | |
'''Same as flatten1 but outputs as a generator in order to handle very | |
large lists. | |
Args: | |
list_ (list): list to be flattened | |
Returns: | |
Generator[int, None, None]: the flattened list. | |
''' | |
for item in list_: | |
if isinstance(item, list): | |
yield from flatten2(item) | |
else: | |
yield item |
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
# Uses PyTest Testing Format | |
from source import flatten1, flatten2 | |
def test_flatten(): | |
testcase = [[1,2,[3]],4,[[5, 6], 7]] | |
funcs = (flatten1, flatten2) | |
for func in funcs: | |
result = func(testcase) | |
for item in result: | |
assert not isinstance(item, list) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment