Skip to content

Instantly share code, notes, and snippets.

@scogle
Created February 12, 2018 18:00
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 scogle/4286877812f31d939ed0d69bfaead842 to your computer and use it in GitHub Desktop.
Save scogle/4286877812f31d939ed0d69bfaead842 to your computer and use it in GitHub Desktop.
import unittest
def flatten(arr):
""" Write some code, that will flatten an array of arbitrarily nested arrays
of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
"""
flattened_arr = []
def recur(el):
if type(el) == list:
for e in el:
recur(e)
elif type(el) == int:
flattened_arr.append(el)
else:
raise TypeError('List elements must be integers or lists')
recur(arr)
return flattened_arr
class TestFlattener(unittest.TestCase):
print(flatten([[1,2,[3]],4]))
def test_flatten(self):
""" Test that the flattener works correctly
"""
test_arr = [[1,2,[3]],4]
res = flatten(test_arr)
self.assertEqual(res, [1,2,3,4])
def test_error(self):
""" Test that the appropriate exception gets raised on bad input
"""
with self.assertRaises(TypeError) as te:
flatten([[1,{'hello': 'world'},['a']],4])
self.assertEqual(type(te.exception), TypeError)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment