Skip to content

Instantly share code, notes, and snippets.

@serenaf
Created May 17, 2015 20:38
Show Gist options
  • Save serenaf/e202ca6590a4428eca01 to your computer and use it in GitHub Desktop.
Save serenaf/e202ca6590a4428eca01 to your computer and use it in GitHub Desktop.
Flatten Array
def flatten_array( array, result ):
""" if the array is empty then return [] """
if not array:
return []
else:
for a in array:
""" if the current index is a number, take this number as part of the flattened result """
if(isinstance(a,int)):
result.append(a)
else:
""" if the current index is an array, recursively call the flatten method for this array"""
flatten_array(a, result)
def main():
result = []
flatten_array([[1,2, 3], [4]], result)
print(result)
if __name__ == '__main__':
main()
import unittest
from flatten_array import flatten_array
class FlattenArrayTests(unittest.TestCase):
""" an empty array is naturally flattened"""
def testEmptyArray(self):
result = []
flatten_array([], result)
self.assertEqual(result, [])
""" an array containing a single number is flattened by taking this number"""
def testSingleNumberArray(self):
result = []
flatten_array([1], result)
self.assertEqual(result, [1])
""" an array within an array is flattened by taking the containing number """
def testArrayInArray(self):
result = []
flatten_array([[1]], result)
self.assertEqual(result, [1])
def main():
unittest.main()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment