I don’t even remember the first code challenge I got in my interviews, but what I’m really sure is… I HATE THEM.
Don’t misunderstand me, I’m just bad at generating an algorithm in the middle of an interview with 30-40 minutes to examine, analyze, create and code a solution. I like to solve problems trough a code challenge, but for me it takes time.
But well , to have a history of what kind of code challenges I got I’m gonna post the challenge and as soon I have a solution I will post it.
This challenge was for a Python position, basically says :
“Sort the next list in a natural order”
filenames = [‘bs1-2.png’, ‘bs1-10.png’, ‘cs1-1.png’, ‘bs1-1.png’, ‘cs1-2.png’, ‘cs1-10.png’]
Natural order means we are expecting to be sorted like this:
['bs1-1.png', 'bs1-2.png', 'bs1-10.png', 'cs1-1.png', 'cs1-2.png', 'cs1-10.png']
So, this means using list.sort() will not give us the expected result.
And many people will say this is an actual easy challenge, well, not for me because I’ve never done this without using a compareTo like method.
Now, since python sort function has a key parameter that acts like the Java compareTo method the documentation is not very clear about what actually the method will receive, and again 20-30 minutes to analyze the problem.
My first approach was to compare every character from every pair of words in a bubble sort -like algorithm, but then this was not viable because you must be sure both words contains the same amount of characters.
Next approach : Ok, so, let’s assume the ascii table assigns a numeric value for every char, what about getting every numeric value from every character in the word, sum everything and compare with the next word value and sort based on this value. But I was not pretty sure if this was viable.
I didn’t get the position of course, but hey, I really did my best trying to find a solution. Then I googled and found I was not too far from the right answer:
- Yes, the key parameter was part of the solution ☑️
- Getting the numeric value of the word was actually… part of the solution : ☑️
filenames = ['bs1-2.png', 'bs1-10.png', 'cs1-1.png', 'bs1-1.png', 'cs1-2.png', 'cs1-10.png'] def natural_key(string_): return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)] filenames.sort(key=natural_key) print(filenames)
Update: What’s going here?
- The key function will divide every string using a regex and put into a list every string fragment, and numbers, and then return the list in order to be compared with another element in the string list.
So well, I will assume I have a lot of work solving challenges, but actually I did better than expected .