Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list of strings by custom key

I recently had a live coding interview, and was asked to solve a relatively simple problem:

Given a list of two-character strings in an arbitrary order, write a function that returns a list of the same strings, sorted first by strings containing both alpha and numeric characters in ascending order, followed by numerical-only strings in ascending order.

I was able to solve this fairly quickly with the below:

polelist = ['13', '2', '20', '3', '30', '1a', '1b', '1', '3c', '2a', 'a1', '2b', '10', 'aa']

def sortpoles(poles):
    alphapoles = []
    numpoles = []

    for item in poles:
        if item.isnumeric():
            numpoles.append(item)
        else:
            alphapoles.append(item)

    numpoles = [int(x) for x in numpoles]
    numpoles.sort()
    numpoles = [str(x) for x in numpoles]

    alphapoles.sort()

    alphapoles.extend(numpoles)

    return alphapoles

This returns: ['1a', '1b', '2a', '2b', '3c', 'a1', 'aa', '1', '2', '3', '10', '13', '20', '30'] which is the correct answer.

With the remaining time, they asked me if I could find a more efficient way to do this. I know that both sort() and sorted() can accept a "key" argument with a function for custom sort criteria, but I wasn't able to figure out the logic to accomplish this. I've been trying to solve this for my own edification for the last couple hours but I'm stumped. Is this even the right approach for improving the efficiency of my solution? Is there a better way I'm not thinking of?

like image 542
LK3K Avatar asked Oct 16 '25 23:10

LK3K


1 Answers

Not the cleanest solution, but does the job.

>>> polelist.sort(key = lambda x : (x.isnumeric(), len(x)))
['1a', '1b', '2a', '2b', '3c', 'a1', 'aa', '1', '2', '3', '10', '13', '20', '30']

The logic is to sort first by bool (is numeric or not), and the by the length of the string as larger numbers --> larger length and numbers of the same length are intrinsically sorted.

like image 160
GIOVANNI QUINONES VALDEZ Avatar answered Oct 18 '25 14:10

GIOVANNI QUINONES VALDEZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!