diff --git a/src/array_utils.py b/src/array_utils.py new file mode 100644 index 0000000..784221b --- /dev/null +++ b/src/array_utils.py @@ -0,0 +1,36 @@ +from typing import List, Union, Any + +def flatten_array(arr: Union[List[Any], Any]) -> List[Any]: + """ + Recursively flatten a nested array into a single-level array. + + Args: + arr (Union[List[Any], Any]): The input array to flatten. + Can contain nested lists or other types of elements. + + Returns: + List[Any]: A flattened list containing all non-list elements. + + Examples: + >>> flatten_array([1, [2, 3], [4, [5, 6]]]) + [1, 2, 3, 4, 5, 6] + >>> flatten_array([]) + [] + >>> flatten_array([1, 2, 3]) + [1, 2, 3] + """ + # Base case: if input is not a list, return it as a single-element list + if not isinstance(arr, list): + return [arr] + + # If the list is empty, return an empty list + if not arr: + return [] + + # Recursive flattening + flattened = [] + for item in arr: + # Recursively flatten each item + flattened.extend(flatten_array(item)) + + return flattened \ No newline at end of file diff --git a/tests/test_array_utils.py b/tests/test_array_utils.py new file mode 100644 index 0000000..7cd3bf9 --- /dev/null +++ b/tests/test_array_utils.py @@ -0,0 +1,30 @@ +import pytest +from src.array_utils import flatten_array + +def test_flatten_simple_list(): + """Test flattening a simple list""" + assert flatten_array([1, 2, 3]) == [1, 2, 3] + +def test_flatten_nested_list(): + """Test flattening a list with one level of nesting""" + assert flatten_array([1, [2, 3], 4]) == [1, 2, 3, 4] + +def test_flatten_deeply_nested_list(): + """Test flattening a list with multiple levels of nesting""" + assert flatten_array([1, [2, [3, 4]], [5, 6]]) == [1, 2, 3, 4, 5, 6] + +def test_flatten_empty_list(): + """Test flattening an empty list""" + assert flatten_array([]) == [] + +def test_flatten_single_element(): + """Test flattening a single non-list element""" + assert flatten_array(5) == [5] + +def test_flatten_mixed_types(): + """Test flattening a list with mixed types and nesting""" + assert flatten_array([1, [2, 'three'], [4.5, [None]]]) == [1, 2, 'three', 4.5, None] + +def test_flatten_complex_nesting(): + """Test flattening a list with complex, irregular nesting""" + assert flatten_array([1, [2, [3, [4]]], 5, [6], [[7]]]) == [1, 2, 3, 4, 5, 6, 7] \ No newline at end of file