Flatten and Sort an Array in Python

The challenge

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

Example:

Given [[3, 2, 1], [4, 6, 5], [], [9, 7, 8]], your function should return [1, 2, 3, 4, 5, 6, 7, 8, 9].

The solution in Python code

Option 1:

def flatten_and_sort(array): a = [] for b in array: for c in b: a.append(c) return sorted(a)
Code language: Python (python)

Option 2:

def flatten_and_sort(array): return sorted([j for i in array for j in i])
Code language: Python (python)

Option 3:

def flatten_and_sort(array): return sorted(sum(array, []))
Code language: Python (python)

Test cases to validate our solution

import test from solution import flatten_and_sort @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(flatten_and_sort([]), []) test.assert_equals(flatten_and_sort([[], []]), []) test.assert_equals(flatten_and_sort([[], [1]]), [1]) test.assert_equals(flatten_and_sort([[3, 2, 1], [7, 9, 8], [6, 4, 5]]), [1, 2, 3, 4, 5, 6, 7, 8, 9]) test.assert_equals(flatten_and_sort([[1, 3, 5], [100], [2, 4, 6]]), [1, 2, 3, 4, 5, 6, 100])
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments