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

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

Args:
arr (Union[List[Any], Any]): The input array to be flattened.

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

Raises:
TypeError: If the input is not a list or does not support iteration.
"""
# Base case: if input is not a list or is a string, return as single-element list
if not isinstance(arr, list) or isinstance(arr, str):
return [arr]

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

return flattened
36 changes: 36 additions & 0 deletions tests/test_array_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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 nested list"""
assert flatten_array([1, [2, 3], 4]) == [1, 2, 3, 4]

def test_flatten_deeply_nested_list():
"""Test flattening a deeply nested list"""
assert flatten_array([1, [2, [3, 4]], 5]) == [1, 2, 3, 4, 5]

def test_flatten_multiple_levels_of_nesting():
"""Test flattening multiple levels of nested lists"""
nested = [1, [2, [3, [4, 5]]], 6]
assert flatten_array(nested) == [1, 2, 3, 4, 5, 6]

def test_flatten_mixed_types():
"""Test flattening a list with mixed types"""
mixed = [1, 'a', [2, [3.14]], {'key': 'value'}]
assert flatten_array(mixed) == [1, 'a', 2, 3.14, {'key': 'value'}]

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

def test_flatten_non_nested_element():
"""Test flattening a non-nested element"""
assert flatten_array(42) == [42]

def test_flatten_string():
"""Test that strings are treated as single elements"""
assert flatten_array('hello') == ['hello']