Created
March 1, 2017 20:20
-
-
Save srathbun/352ce73bd5a999c6d10c4fc8e8bf1a43 to your computer and use it in GitHub Desktop.
A python flatten function for arbitrarily nested arrays
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(listOfLists): | |
""" | |
Flatten arbitrary levels of nesting for an array of integers. | |
Any non list, non int value throws an exception. | |
""" | |
results = [] | |
for item in listOfLists: | |
if isinstance(item, int): | |
results.append(item) | |
if isinstance(item, list): | |
for value in flatten(item): | |
results.append(value) | |
else: | |
raise Exception("Not a list or integer: {}".format(item)) | |
return results |
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
import unittest | |
from flatten import flatten | |
class TestFlatten(unittest.TestCase): | |
def test_success(self): | |
testList = [ 1, [1,2,[1,2,3]], 4, [234]] | |
self.assertSequenceEqual(flatten(testList), [ 1,1,2,1,2,3,4,234 ]) | |
def test_fail(self): | |
testList = [ 1, 4, ['abc']] | |
with self.assertRaises(Exception): | |
flatten(testList) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment