Skip to content

Instantly share code, notes, and snippets.

@guitarmanvt
Created February 11, 2019 18:26
Show Gist options
  • Save guitarmanvt/82c267fe7c1915a8020175f58ca32257 to your computer and use it in GitHub Desktop.
Save guitarmanvt/82c267fe7c1915a8020175f58ca32257 to your computer and use it in GitHub Desktop.
import unittest
def flatten(it):
"""Flatten an arbitrarily-nested list of integers into a single list.
Args:
it (list)
Returns: list of integers
"""
flat = []
for x in it:
if type(x) is int:
flat.append(x)
else:
flat.extend(flatten(x))
return flat
class TestFlatten(unittest.TestCase):
def _test(self, inputs, expected):
self.assertEqual(list(flatten(inputs)), expected)
def test_empty_list(self):
self._test([], [])
def test_one_level(self):
self._test([1, 2, 3], [1, 2, 3])
def test_nested_lists(self):
self._test([[1,2,[3]],4], [1,2,3,4])
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment