This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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