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

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

Args:
arr (Union[List[Any], Any]): The input array to flatten.
Can contain nested lists or other types of elements.

Returns:
List[Any]: A flattened list containing all non-list elements.

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]
"""
# Base case: if input is not a list, return it as a single-element list
if not isinstance(arr, list):
return [arr]

# If the list is empty, return an empty list
if not arr:
return []

# Recursive flattening
flattened = []
for item in arr:
# Recursively flatten each item
flattened.extend(flatten_array(item))

return flattened
30 changes: 30 additions & 0 deletions tests/test_array_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import pytest
from src.array_utils 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, 6]]) == [1, 2, 3, 4, 5, 6]

def test_flatten_empty_list():
"""Test flattening an empty list"""
assert flatten_array([]) == []

def test_flatten_single_element():
"""Test flattening a single non-list element"""
assert flatten_array(5) == [5]

def test_flatten_mixed_types():
"""Test flattening a list with mixed types and nesting"""
assert flatten_array([1, [2, 'three'], [4.5, [None]]]) == [1, 2, 'three', 4.5, None]

def test_flatten_complex_nesting():
"""Test flattening a list with complex, irregular nesting"""
assert flatten_array([1, [2, [3, [4]]], 5, [6], [[7]]]) == [1, 2, 3, 4, 5, 6, 7]