나는 이렇게 학습한다/Algorithm & SQL

Flatten and sort an array

daco2020 2022. 8. 20. 11:08
반응형

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].

 

 

Solution:

def flatten_and_sort(array):
    arr = []
    for i in array:
        arr.extend(i)
    return sorted(arr)

 

 

Other Solution:

from itertools import chain
def flatten_and_sort(array):
    return sorted((chain(*array)))

How to solve a built-in function

 

 

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

How to solve it with options of sum

 

반응형

'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글

Deodorant Evaporator  (0) 2022.08.22
Sum of Minimums!  (0) 2022.08.21
Find the stray number  (0) 2022.08.19
5 without numbers !!  (0) 2022.08.19
If you can't sleep, just count sheep!!  (0) 2022.08.17