Skip to content

Instantly share code, notes, and snippets.

@kishan3
Last active November 6, 2018 13:22
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 kishan3/2b87eb5a50c0a09077ee73037d452880 to your computer and use it in GitHub Desktop.
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.
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())
@kishan3
Copy link
Author

kishan3 commented Nov 6, 2018

This can be run using python3 array_flatten.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment