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
31 changes: 31 additions & 0 deletions src/array_flatten.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from typing import List, Union, Any

def flatten_array(arr: List[Any]) -> List[Any]:
"""
Recursively flatten a nested array of arbitrary depth into a single-level array.

Args:
arr (List[Any]): A nested list that may contain other lists or nested lists.

Returns:
List[Any]: A flattened list with all nested elements at the top level.

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 arr:
# 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
26 changes: 26 additions & 0 deletions tests/test_array_flatten.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import pytest
from src.array_flatten import flatten_array

def test_flatten_empty_array():
"""Test flattening an empty array."""
assert flatten_array([]) == []

def test_flatten_single_level_array():
"""Test flattening an already flat array."""
assert flatten_array([1, 2, 3]) == [1, 2, 3]

def test_flatten_simple_nested_array():
"""Test flattening a simply 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, 6]]) == [1, 2, 3, 4, 5, 6]

def test_flatten_mixed_nested_array():
"""Test flattening an array with various nesting levels."""
assert flatten_array([1, [2, 3, [4, 5]], 6, [7, [8, 9]]]) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def test_flatten_array_with_different_types():
"""Test flattening an array with different types of elements."""
assert flatten_array([1, ['a', 'b'], [2, ['c']]]) == [1, 'a', 'b', 2, 'c']