Created
September 19, 2016 17:17
-
-
Save IslandUsurper/db24646df39227e8b9caa99115c7a86f to your computer and use it in GitHub Desktop.
Flatten an arbitrarily 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(items): | |
""" | |
Flatten a nested list of integers. | |
Passing a non-list instead returns a list containing the argument. | |
""" | |
if not isinstance(items, list): | |
return [items] | |
result = [] | |
for i in items: | |
for x in flatten(i): | |
result.append(x) | |
return result | |
# Use pytest to run this function. | |
def test_flatten(): | |
assert flatten(10) == [10] | |
assert flatten([3]) == [3] | |
assert flatten([4, 2, 5]) == [4, 2, 5] | |
assert flatten([1, 2, [3, 4]]) == [1, 2, 3, 4] | |
assert flatten([[1], [2, 4, [5, 2]], 31, [15, 2]]) == [1, 2, 4, 5, 2, 31, 15, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment