Created
December 24, 2017 16:20
-
-
Save keshavbahadoor/3c06b2bf028ca3d4d17bfe88b159df8c to your computer and use it in GitHub Desktop.
Flatten Array in Python without language specific
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
def flatten_array(array, result=None): | |
""" | |
Flatten a given array of arbitrarily nested arrays of integers. | |
e.g. [[1,2,[3]],4] -> [1,2,3,4] | |
:param array: Input array to flatten | |
:param result: Starting result array. Can be omitted. | |
:return: Flattened array | |
""" | |
try: | |
if not isinstance(array, list) and not isinstance(array, (int, long)): | |
print 'array parameter is not in appropriate format' | |
return [] | |
if not isinstance(result, list): | |
result = [] | |
for item in array: | |
if isinstance(item, list): | |
flatten_array(item, result) | |
elif not isinstance(item, (int, long)): | |
print 'array element \'{}\' is not numeric'.format(item) | |
return [] | |
else: | |
result.append(item) | |
return result | |
except Exception, e: | |
print e | |
return [] | |
# Example usage | |
print flatten_array([[1, 2, [3]], 4]) | |
print flatten_array([1, 2, [3, [4, 5, [6, 7]], [8]]]) | |
print flatten_array('something') | |
print flatten_array([1, 2, [3], 'a', [4]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment