The goal is to flatten an array of nested arrays of integers.
For example [1, [2], [3, [4]]]
should return [1, 2, 3, 4]
I'm particularly looking for some feedback on the following:
- Is usage of
TypeError
exception justified? - Did I miss some valid edge cases in my tests?
Here is my solution including unit tests:
#!/usr/bin/env python
import unittest
def flatten_list(array):
""" Returns a flattened array of integers from arbitrarily nested arrays of integers.
>>> flatten_list([[1, 2, [3]], 4])
[1, 2, 3, 4]
"""
flat_array = []
for element in array:
if isinstance(element, int):
flat_array.append(element)
elif isinstance(element, list):
flat_array += flatten_list(element)
else:
raise TypeError("Unsupported type ({})".format(
type(element).__name__))
return flat_array
class FlattenListTestCase(unittest.TestCase):
"""Tests for flatten_list"""
def test_empty_list(self):
self.assertEqual(flatten_list([]), [])
def test_single_integer(self):
self.assertEqual(flatten_list([3]), [3])
def test_already_flattened(self):
self.assertEqual(flatten_list([1, 2, 3, 4]), [1, 2, 3, 4])
def test_single_element_multiple_nested(self):
self.assertEqual(flatten_list([[1]]), [1])
def test_arbitary(self):
self.assertEqual(flatten_list(
[1, [2], [3, 4], [[5]], 6]), [1, 2, 3, 4, 5, 6])
def test_empty_sublists(self):
self.assertEqual(flatten_list([1, [[], 2]]), [1, 2])
self.assertEqual(flatten_list([[]]), [])
def test_invalid_input(self):
with self.assertRaises(TypeError):
flatten_list(3)
with self.assertRaises(TypeError):
flatten_list([3, "2"])
with self.assertRaises(TypeError):
flatten_list(None)
if __name__ == '__main__':
unittest.main()