Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/array_flattener.py
Original file line number Diff line number Diff line change
@@ -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
38 changes: 38 additions & 0 deletions tests/test_array_flattener.py
Original file line number Diff line number Diff line change
@@ -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]