Skip to content

Instantly share code, notes, and snippets.

@fpischedda
Created November 7, 2017 12:59
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 fpischedda/842e55d20e7023364083aba2d386fbd5 to your computer and use it in GitHub Desktop.
Save fpischedda/842e55d20e7023364083aba2d386fbd5 to your computer and use it in GitHub Desktop.
"""
flatten.py
Problem:
given an arbitarily nested list return a flattened list
Unit test included in the module itself for simplicity
Works with python2 and python3
"""
import unittest
def flatten(nested):
"returns a flattened version of the provided list"
if nested is None:
raise TypeError("Cannot flatten a None object")
if not isinstance(nested, list):
raise TypeError("Cannot flatten a non list object")
flattened = []
for element in nested:
if isinstance(element, list):
flattened.extend(flatten(element))
else:
flattened.append(element)
return flattened
class TestFlattenFunction(unittest.TestCase):
def test_none_parameter(self):
with self.assertRaises(TypeError):
flatten(None)
def test_not_list_parameter(self):
with self.assertRaises(TypeError):
flatten('not a list')
def test_flatten(self):
to_flatten = [1, 2, 3, [4], 5, [6, [7, 8, [9, [10]]]]]
self.assertEqual(flatten(to_flatten), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment