Python-Coding-Challenge

[Coding-Challenge-Python/Flatten-Array · GitHub]

Here is my solution for the Python3 Coding Challenge- Flatten possible multi-dimensional array
I included two possible ways to check is and element in an array is an array:

  1. type()
  2. isinstance()
def flatten_array(arr): # Write your code here flat_list = [] # Iterate through the outer list for element in arr: #if type(element) is list: if isinstance(element, list): # If the element is of type list, iterate through the sublist or inner list for item in element: flat_list.append(item) else: flat_list.append(element) return flat_list print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9])) print(flatten_array([[2], [8, 9, 10,], 5, 4, []] ))
2 Likes

Here’s a one-liner using the built-in collections and itertools modules.

import collections.abc
from itertools import chain


def flatten_array(arr):
    return list(chain.from_iterable(n if isinstance(n, collections.abc.Iterable) and
                                         not isinstance(n, str) else [n] for n in arr))


if __name__ == '__main__':
    print(flatten_array([1, 2, [3, 4, 5], 6, [7, 8], 9]))  # [1, 2, 3, 4, 5, 6, 7, 8, 9]
    print(flatten_array([[2], [8, 9, 10, ], 5, 4, []]))  # [2, 8, 9, 10, 5, 4]