Last active
January 16, 2019 09:21
-
-
Save saurabh-hirani/6f3d7f242d4423f9d2d5f9de4b5a5277 to your computer and use it in GitHub Desktop.
Flatten a nested array
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
def flatten(arr): | |
""" | |
Flatten a nested array | |
>>> flatten([1, 2, 3]) | |
[1, 2, 3] | |
>>> flatten([1,2,3,[1,2,3]]) | |
[1, 2, 3, 1, 2, 3] | |
>>> flatten([1,2,3,[1,2,[4,5,6],3]]) | |
[1, 2, 3, 1, 2, 4, 5, 6, 3] | |
""" | |
flattened_arr = [] | |
for elem in arr: | |
if not isinstance(elem, list): | |
flattened_arr.append(elem) | |
else: | |
[flattened_arr.append(i) for i in flatten(elem)] | |
return flattened_arr | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Neat! Was looking for this. Good to learn about doctest as well.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This problem could also be a good use case for the yield statement.