diff --git a/src/array_flattener.py b/src/array_flattener.py new file mode 100644 index 00000000..8f0a9a36 --- /dev/null +++ b/src/array_flattener.py @@ -0,0 +1,31 @@ +from typing import List, Union, Any + +def flatten_array(nested_list: List[Any]) -> List[Any]: + """ + Recursively flatten a nested list of arbitrary depth. + + Args: + nested_list (List[Any]): A potentially nested list to be flattened. + + Returns: + List[Any]: A flattened list with all nested elements extracted. + + 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] + """ + flattened = [] + + for item in nested_list: + # If the item is a list, recursively flatten it + if isinstance(item, list): + flattened.extend(flatten_array(item)) + else: + # If not a list, add the item directly + flattened.append(item) + + return flattened \ No newline at end of file diff --git a/tests/test_array_flattener.py b/tests/test_array_flattener.py new file mode 100644 index 00000000..9966b9b0 --- /dev/null +++ b/tests/test_array_flattener.py @@ -0,0 +1,31 @@ +import pytest +from src.array_flattener import flatten_array + +def test_flatten_simple_nested_list(): + """Test flattening a simple nested list.""" + input_list = [1, [2, 3], 4] + assert flatten_array(input_list) == [1, 2, 3, 4] + +def test_flatten_deeply_nested_list(): + """Test flattening a deeply nested list.""" + input_list = [1, [2, [3, 4]], [5, [6, 7]]] + assert flatten_array(input_list) == [1, 2, 3, 4, 5, 6, 7] + +def test_flatten_empty_list(): + """Test flattening an empty list.""" + assert flatten_array([]) == [] + +def test_flatten_no_nesting(): + """Test flattening a list with no nesting.""" + input_list = [1, 2, 3, 4, 5] + assert flatten_array(input_list) == [1, 2, 3, 4, 5] + +def test_flatten_mixed_types(): + """Test flattening a list with mixed types and nesting.""" + input_list = [1, 'a', [2, 'b'], [3, [4, 'c']]] + assert flatten_array(input_list) == [1, 'a', 2, 'b', 3, 4, 'c'] + +def test_flatten_single_element_lists(): + """Test flattening lists with single-element nested lists.""" + input_list = [[1], [2], [3]] + assert flatten_array(input_list) == [1, 2, 3] \ No newline at end of file