Last active
December 16, 2020 12:57
-
-
Save Alir3z4/8659fd1daf6d33dfbfe8902e3c024c49 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers.
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
from typing import List | |
def flatten_list(items: List) -> List[int]: | |
""" | |
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]. | |
>>> nested: list = [[1, 2, [3, [4, 4, 8, [8, 8, 7]]]], 4, [], None] | |
>>> expected: List[int] = [1, 2, 3, 4, 4, 8, 8, 8, 7, 4] | |
>>> assert flatten_list(nested) == expected | |
""" | |
flatten: List[int] = [] | |
for item in items: | |
if isinstance(item, list): | |
flatten.extend(flatten_list(item)) | |
elif isinstance(item, int): | |
flatten.append(item) | |
return flatten | |
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
from typing import List | |
from flatten import flatten_list | |
def test_flatten() -> None: | |
nested: list = [[1, 2, [3, [4, 4, 8, [8, 8, 7]]]], 4, [], None] | |
expected: List[int] = [1, 2, 3, 4, 4, 8, 8, 8, 7, 4] | |
assert flatten_list(nested) == expected | |
if __name__ == "__main__": | |
test_flatten() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment