Created
August 23, 2017 09:23
-
-
Save mllopart/f2b7e1456a92d9aecb8093f0f0f0ad22 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]
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 | |
#Function takes an array of arbitrarily nested arrays of int and flattens it | |
#into a 1 dimensional array containing the same integers. | |
def flatten_array(array_to_flatten): | |
new_array = [] | |
#we check each element, if it's an INT we append it into the output arr | |
#if it's not an int, we recursively call the function to flattern it | |
for element in array_to_flatten: | |
if type(element) is int: | |
new_array.append(element) | |
else: | |
new_array += flatten_array(element) | |
return new_array | |
#Test class for the created function flatten_array | |
class FlattenArrayTestScript(unittest.TestCase): | |
def test_simple(self): | |
self.assertEqual([1,2,3,4], flatten_array([1,2,3,4])) | |
def test_citrusbyte(self): | |
self.assertEqual([1,2,3,4], flatten_array([[1,2,[3]],4])) | |
if __name__=="__main__": | |
unittest.main() | |
""" | |
>> python flatten_array.py | |
---------------------------------------------------------------------- | |
Ran 2 tests in 0.000s | |
OK | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment