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_flattener.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
from typing import List, Union, Any

def flatten_array(nested_list: List[Any]) -> List[Any]:
"""
Recursively flatten a nested list of arbitrary depth.

Args:
nested_list (List[Any]): A potentially nested list to be flattened.

Returns:
List[Any]: A flattened list with all nested elements extracted.

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

def test_flatten_simple_nested_list():
"""Test flattening a simple nested list."""
input_list = [1, [2, 3], 4]
assert flatten_array(input_list) == [1, 2, 3, 4]

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

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

def test_flatten_no_nesting():
"""Test flattening a list with no nesting."""
input_list = [1, 2, 3, 4, 5]
assert flatten_array(input_list) == [1, 2, 3, 4, 5]

def test_flatten_mixed_types():
"""Test flattening a list with mixed types and nesting."""
input_list = [1, 'a', [2, 'b'], [3, [4, 'c']]]
assert flatten_array(input_list) == [1, 'a', 2, 'b', 3, 4, 'c']

def test_flatten_single_element_lists():
"""Test flattening lists with single-element nested lists."""
input_list = [[1], [2], [3]]
assert flatten_array(input_list) == [1, 2, 3]