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?
sort'skey) here, this is more of a code review question than an SO question. I'd recommend asking the same question here: codereview.stackexchange.com