Created
April 1, 2016 17:55
-
-
Save ProProgrammer/9d5dd3b09413fb0e5f35ba65c1dc6dff to your computer and use it in GitHub Desktop.
Flatten a list using Python with test cases against the flatten function
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
def flatten(input_list): | |
flattened_output = [] | |
for item in input_list: | |
if isinstance(item, int): | |
flattened_output.append(item) | |
else: | |
flattened_output += flatten(item) | |
return flattened_output | |
# In all tests below, the assumption is, the lists contain only integers and no other types of data. | |
# Tests are written to run using py.test | |
def test_flatten_empty_list(): | |
""" | |
assert empty list remains as it is | |
""" | |
input_list = [] | |
assert flatten(input_list) == input_list | |
def test_flatten_no_nested_list(): | |
""" | |
assert non empty list of integers with no nested lists inside it | |
""" | |
input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1000, 100000, 1223456] | |
assert flatten(input_list) == input_list | |
def test_flatten_nested_list_of_integers(): | |
""" | |
assert non empty list of integers and a few nested lists | |
""" | |
input_list = [1, 2, [3, 4], 5, 6, 7, 8, 9, 10, 100, 1000, [100000, 1223456]] | |
expected_value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1000, 100000, 1223456] | |
assert flatten(input_list) == expected_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment