Skip to content

Instantly share code, notes, and snippets.

@srathbun
Created March 1, 2017 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srathbun/352ce73bd5a999c6d10c4fc8e8bf1a43 to your computer and use it in GitHub Desktop.
Save srathbun/352ce73bd5a999c6d10c4fc8e8bf1a43 to your computer and use it in GitHub Desktop.
A python flatten function for arbitrarily nested arrays
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
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