나는 이렇게 학습한다/Algorithm & SQL
Sort array by string length
daco2020
2022. 4. 29. 21:55
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)