Created
April 11, 2022 17:37
-
-
Save vlad-bezden/55c016e752eafb1badba0c80e648eda0 to your computer and use it in GitHub Desktop.
Flatten multi-level nested iterable (list, tuple, ...)
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
"""Flatten multy-level nested iterable.""" | |
from typing import Any, Iterable | |
def deep_flatten(data: Iterable[Any]) -> Iterable[float]: | |
def inner(data): | |
if isinstance(data, (int, float)): | |
return [data] | |
elif not data: | |
return [] | |
first, *tail = data | |
return inner(first) + inner(tail) | |
return inner(data) | |
if __name__ == "__main__": | |
tests = ( | |
([], []), | |
([[[1, 2], [3, 4, 5]], [[[[6, 7]]]], [8], []], [1, 2, 3, 4, 5, 6, 7, 8]), | |
([[1, 2], [3, 4], [5]], [1, 2, 3, 4, 5]), | |
) | |
for test in tests: | |
input, expected = test | |
result = deep_flatten(input) | |
assert result == expected | |
print("PASSED!!!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment