Last active
November 6, 2018 13:22
-
-
Save kishan3/2b87eb5a50c0a09077ee73037d452880 to your computer and use it in GitHub Desktop.
Flatten input list of lists given by user and out put a flattened list.
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 ast | |
import sys | |
import unittest | |
def flatten(items): | |
"""Generator for thwoing our items from list of lists.""" | |
for x in items: | |
if isinstance(x, list): | |
for sub_x in flatten(x): | |
yield sub_x | |
else: | |
yield x | |
class TestFlatten(unittest.TestCase): | |
"""Unit tests for flatten method.""" | |
def test_empty_list(self): | |
self.assertEquals(list(flatten('')), []) | |
def test_list_of_lists(self): | |
self.assertEquals(list(flatten([[1, 2, 3], [4, [5, 6]], [7], [8, [9]]])), [1, 2, 3, 4, 5, 6, 7, 8, 9]) | |
class MustBeAListError(ValueError): | |
pass | |
def main(): | |
input_list = input("Enter the list you want to flatten: ") | |
if not input_list: | |
return [] | |
if sys.version_info > (3, 0): | |
input_list = ast.literal_eval(input_list) | |
if type(input_list) is not list: | |
raise MustBeAListError("Input to flatten must be a list.") | |
flat_list_generator = flatten(input_list) | |
return list(flat_list_generator) | |
if __name__ == '__main__': | |
test_object = TestFlatten() | |
test_object.test_empty_list() | |
test_object.test_list_of_lists() | |
print(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This can be run using
python3 array_flatten.py