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
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pytest==7.3.1
38 changes: 38 additions & 0 deletions src/array_flatten.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from typing import List, Union

def flatten_array(arr: List[Union[int, List]]) -> List[int]:
"""
Flatten a nested list of integers into a single-level list.

This function recursively flattens a list that may contain nested lists
of integers into a single-level list of integers.

Args:
arr (List[Union[int, List]]): A list that may contain integers or nested lists

Returns:
List[int]: A flattened list of integers

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 flattened list
elif isinstance(item, int):
flattened.append(item)
else:
# Raise an error for non-integer and non-list elements
raise TypeError(f"Unsupported type in array: {type(item)}")

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

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

def test_flatten_list_with_empty_sublists():
"""Test flattening a list with empty sublists"""
assert flatten_array([1, [], [2, []], 3]) == [1, 2, 3]

def test_invalid_type_raises_error():
"""Test that non-integer, non-list elements raise a TypeError"""
with pytest.raises(TypeError):
flatten_array([1, 2, "3"])

def test_nested_invalid_type_raises_error():
"""Test that nested invalid types also raise a TypeError"""
with pytest.raises(TypeError):
flatten_array([1, [2, "3"], 4])

def test_multiple_nested_levels():
"""Test flattening a list with multiple nested levels"""
assert flatten_array([1, [2, [3, [4, 5]]], 6]) == [1, 2, 3, 4, 5, 6]