물음표 살인마의 개발블로그

알고리즘 문제/CodeWar

Sort array by string length

BEstyle 2022. 11. 21. 15:01

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.


def sort_by_length(arr):
    length=len(arr)
    loc=0
    ans=[]
    for j in range(length):
        max=1000
        for i in range(len(arr)):
            if len(arr[i])<max:
                max=len(arr[i])
                loc=i
        ans.append(arr[loc])
        arr.remove(arr[loc])
    return ans

'알고리즘 문제 > CodeWar' 카테고리의 다른 글

Irreducible Sum of Rationals  (0) 2022.11.22
Integer Depth  (0) 2022.11.22
Run-length encoding  (1) 2022.11.20
Descending Order  (0) 2022.11.20
Highest Rank Number in an Array  (0) 2022.11.19