Monday, April 15, 2024
HomeSoftware EngineeringFlatten and Type an Array in Python

# Flatten and Type an Array in Python

## The problem#

Given a two-dimensional array of integers, return the flattened model of the array with all of the integers within the sorted (ascending) order.

Instance:

Given [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]], your operate ought to return [1, 2, 3, 4, 5, 6, 7, 8, 9].

## The answer in Python code#

Possibility 1:

``````def flatten_and_sort(array):
a = []
for b in array:
for c in b:
a.append(c)
return sorted(a)
``````

Possibility 2:

``````def flatten_and_sort(array):
return sorted([j for i in array for j in i])
``````

Possibility 3:

``````def flatten_and_sort(array):
return sorted(sum(array, []))
``````

## Check circumstances to validate our answer#

``````import check
from answer import flatten_and_sort

@check.describe("Fastened Checks")
def fixed_tests():
@check.it('Fundamental Check Circumstances')
def basic_test_cases():
check.assert_equals(flatten_and_sort([]), [])
check.assert_equals(flatten_and_sort([[], []]), [])
check.assert_equals(flatten_and_sort([[], [1]]), [1])
check.assert_equals(flatten_and_sort([[3, 2, 1], [7, 9, 8], [6, 4, 5]]), [1, 2, 3, 4, 5, 6, 7, 8, 9])
check.assert_equals(flatten_and_sort([[1, 3, 5], [100], [2, 4, 6]]), [1, 2, 3, 4, 5, 6, 100])
``````
RELATED ARTICLES