diff --git a/src/array_flattener.py b/src/array_flattener.py new file mode 100644 index 00000000..863a51ab --- /dev/null +++ b/src/array_flattener.py @@ -0,0 +1,35 @@ +from typing import List, Union + +def flatten_array(arr: List[Union[int, List]]) -> List[int]: + """ + Recursively flatten a nested array of integers. + + Args: + arr (List[Union[int, List]]): A potentially nested list of integers. + + Returns: + List[int]: A flattened list containing all integers from the input. + + Raises: + TypeError: If the input contains non-integer and non-list elements. + + Examples: + >>> flatten_array([1, [2, 3], 4]) + [1, 2, 3, 4] + >>> flatten_array([1, [2, [3, 4]], 5]) + [1, 2, 3, 4, 5] + """ + flattened = [] + + for item in arr: + # If the item is a list, recursively flatten it + if isinstance(item, list): + flattened.extend(flatten_array(item)) + # If the item is an integer, add it to the result + elif isinstance(item, int): + flattened.append(item) + # Raise an error for any other type + else: + raise TypeError(f"Unsupported type in array: {type(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..a06d42e4 --- /dev/null +++ b/tests/test_array_flattener.py @@ -0,0 +1,38 @@ +import pytest +from src.array_flattener import flatten_array + +def test_flatten_simple_array(): + """Test flattening a simple array.""" + assert flatten_array([1, 2, 3]) == [1, 2, 3] + +def test_flatten_nested_array(): + """Test flattening a nested array.""" + assert flatten_array([1, [2, 3], 4]) == [1, 2, 3, 4] + +def test_flatten_deeply_nested_array(): + """Test flattening a deeply nested array.""" + assert flatten_array([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5] + +def test_flatten_empty_array(): + """Test flattening an empty array.""" + assert flatten_array([]) == [] + +def test_flatten_single_element_array(): + """Test flattening an array with a single element.""" + assert flatten_array([42]) == [42] + +def test_flatten_multiple_levels_of_nesting(): + """Test flattening an array with multiple levels of nesting.""" + assert flatten_array([1, [2, [3, [4, 5]]], 6]) == [1, 2, 3, 4, 5, 6] + +def test_unsupported_type_raises_error(): + """Test that an error is raised for unsupported types.""" + with pytest.raises(TypeError): + flatten_array([1, 2, "3"]) + + with pytest.raises(TypeError): + flatten_array([1, [2, 3.14], 4]) + +def test_mixed_nesting_with_integers(): + """Test flattening an array with mixed nesting.""" + assert flatten_array([1, [], [2, 3], [[4]], 5]) == [1, 2, 3, 4, 5] \ No newline at end of file