diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..a6510db8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +pytest==7.3.1 \ No newline at end of file diff --git a/src/array_flatten.py b/src/array_flatten.py new file mode 100644 index 00000000..9f69f4a5 --- /dev/null +++ b/src/array_flatten.py @@ -0,0 +1,38 @@ +from typing import List, Union + +def flatten_array(arr: List[Union[int, List]]) -> List[int]: + """ + Flatten a nested list of integers into a single-level list. + + This function recursively flattens a list that may contain nested lists + of integers into a single-level list of integers. + + Args: + arr (List[Union[int, List]]): A list that may contain integers or nested lists + + Returns: + List[int]: A flattened list of integers + + 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 flattened list + elif isinstance(item, int): + flattened.append(item) + else: + # Raise an error for non-integer and non-list elements + raise TypeError(f"Unsupported type in array: {type(item)}") + + return flattened \ No newline at end of file diff --git a/tests/test_array_flatten.py b/tests/test_array_flatten.py new file mode 100644 index 00000000..d8962adf --- /dev/null +++ b/tests/test_array_flatten.py @@ -0,0 +1,36 @@ +import pytest +from src.array_flatten 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]) == [1, 2, 3, 4, 5] + +def test_flatten_empty_list(): + """Test flattening an empty list""" + assert flatten_array([]) == [] + +def test_flatten_list_with_empty_sublists(): + """Test flattening a list with empty sublists""" + assert flatten_array([1, [], [2, []], 3]) == [1, 2, 3] + +def test_invalid_type_raises_error(): + """Test that non-integer, non-list elements raise a TypeError""" + with pytest.raises(TypeError): + flatten_array([1, 2, "3"]) + +def test_nested_invalid_type_raises_error(): + """Test that nested invalid types also raise a TypeError""" + with pytest.raises(TypeError): + flatten_array([1, [2, "3"], 4]) + +def test_multiple_nested_levels(): + """Test flattening a list with multiple nested levels""" + assert flatten_array([1, [2, [3, [4, 5]]], 6]) == [1, 2, 3, 4, 5, 6] \ No newline at end of file