Created
February 11, 2019 18:26
-
-
Save guitarmanvt/82c267fe7c1915a8020175f58ca32257 to your computer and use it in GitHub Desktop.
This file contains hidden or 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(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