Created
December 10, 2017 12:00
-
-
Save floydkots/3fd9d1fd6e78ebc4d6f4484ecfb6ab49 to your computer and use it in GitHub Desktop.
Sample python code to flatten an array of arbitrarily nested arrays of integers into a flat array of integers
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
""" | |
Author: Floyd Kots ~ github.com/floydkots | |
This module contains the flatten_array function | |
""" | |
def flatten_array(array): | |
""" | |
Flatten an array of arbitrarily nested arrays of integers | |
into a flat array of integers | |
:param array: The nested array to flatten | |
:return: A flat array of integers | |
""" | |
if len(array) == 0: | |
return [] | |
if len(array) == 1: | |
return array | |
flat_array = [] | |
for item in array: | |
if isinstance(item, list): | |
flat_array.extend(flatten_array(item)) | |
else: | |
flat_array.append(item) | |
return flat_array |
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
""" | |
Author: Floyd Kots ~ github.com/floydkots | |
This module contains unit tests to check the flatten_array function from flattenArray.py module | |
""" | |
from unittest import TestCase | |
from flattenArray import flatten_array | |
class FlattenArrayTest(TestCase): | |
def testReturnsEmptyArray(self): | |
self.assertEqual([], flatten_array([])) | |
def testFlattensSingleItemArray(self): | |
self.assertEqual([1], flatten_array([1])) | |
def testFlattensSingleLevelArray(self): | |
self.assertEqual([1, 2, 3], flatten_array([1, 2, 3])) | |
def testFlattensTwoLevelNestedArray(self): | |
self.assertEqual([1, 2, 3, 4], flatten_array([1, 2, [3, 4]])) | |
def testFlattensThreeLevelNestedArray(self): | |
self.assertEqual([1, 2, 3, 4, 5], flatten_array([[1, [2, 3]], 4, [5]])) | |
def testFlattensGivenArray(self): | |
self.assertEqual([1, 2, 3, 4], flatten_array([[1, 2, [3]], 4])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment