반응형
Description:
Write a function that takes an array of strings as an argument and returns a sorted array containing the same strings, ordered from shortest to longest.
For example, if this array were passed as an argument:
["Telescopes", "Glasses", "Eyes", "Monocles"]
Your function would return the following array:
["Eyes", "Glasses", "Monocles", "Telescopes"]
All of the strings in the array passed to your function will be different lengths, so you will not have to decide how to order multiple strings of the same length.
Solution:
1. Make a dictionary of the elements of the array and the lengths of the elements.
2. After sorting by length, only the key is added to the list.
3. Return the created list.
def sort_by_length(arr):
dict = {v:l for l, v in zip(map(len, arr),arr)}
return [i for i, _ in sorted(dict.items(), key=lambda x:x[1])]
Best Practice:
def sort_by_length(arr):
return sorted(arr, key=len)
반응형
'나는 이렇게 학습한다 > Algorithm & SQL' 카테고리의 다른 글
Find the vowels (0) | 2022.05.01 |
---|---|
Odd or Even? (0) | 2022.04.30 |
Sum of odd numbers (0) | 2022.04.28 |
Mumbling (0) | 2022.04.27 |
Two to One (0) | 2022.04.26 |