Last active
February 14, 2018 03:37
-
-
Save voodoonofx/358c81343a9b2d09478b5df9d6ccdaab to your computer and use it in GitHub Desktop.
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 collections | |
def flatten(thing): | |
""" | |
Given an arbitrarily nested list, flattens it into a giant list. | |
Args: | |
thing (:obj:`list`): | |
Returns: | |
Generator of elements found within the original :obj:`list` as a stream of elements. | |
""" | |
for foo in thing: | |
if isinstance(foo, collections.Iterable) and not isinstance(foo, basestring): | |
for bar in flatten(foo): | |
yield bar | |
else: | |
yield foo |
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 | |
from flattener import flatten | |
class FlattenTest(unittest.TestCase): | |
""" Test cases for flattener.flatten method """ | |
def testEmptyList(self): | |
""" Test case: Flatten an empty list. Should return empty list """ | |
foo = [] | |
assert list(flatten(foo)) == foo, 'flatten an empty list did not return an empty list.' | |
def testSimpleList(self): | |
""" Test case: flatten an already flattened list. Should return original list """ | |
foo = [1, 2, 3, 4] | |
assert list(flatten(foo)) == foo, 'flatten a shallow list did not return same shallow list.' | |
def testComplexList(self): | |
""" Test case: flatten a complex list, of varying types """ | |
foo = [[1, 2, [3]], 4] | |
assert list(flatten(foo)) == [1, 2, 3, 4], 'flatten complex list from interview question did not return [1, 2, 3, 4].' | |
def testDifferingTypesList(self): | |
""" | |
Test case: flatten a list of varying types. | |
Note, this case showed a critical bug when not checking for string types, which are iterables. | |
""" | |
foo = [1, [2.0, 'three', ['four', ('five', 'six')]]] | |
assert list(flatten(foo)) == [1, 2.0, 'three', 'four', 'five', 'six'], 'flatten mixed type list did not return flattened list.' | |
if __name__ == "__main__": | |
unittest.main() # run all tests |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment