Earlier this year I had an interview through Google Hangouts. I was given a very simple coding question that went something like, “Given an array, write a function that returns the index of the highest value in the array. Your choice of language.”
Easy, right? Well I chose to do it in Python – because why wouldn’t you? Here’s what I did:
Hmmm. Looks like someone learned C and then Python. I talked through what I was doing and I think that’s probably all that was needed for this simple interview problem. I think I mentioned ‘enumerate’ as an aside along with the possibility of using a generator for a very large array that we didn’t want to keep in memory – the latter being a representation of my fleeting grasp of the concept.
I always wanted to go back and do it more Pythonic. Then Dan Bader had a great blog post on the subject and I thought, hey I was gonna do that! So without reproducing his work, I made a few of my own solutions. Here they are:
The ‘index’ method is nice and succinct. And very readable. Two lines! Now let’s get fancy with enumerate. I’m going to skip the perhaps more readable for loops and use list comprehensions to keep the line count down:
Not bad! This one loops over the list of tuples created by ‘enumerate’ – tuples of (index, value). At each (index, value) pair it asks if the value, x[1], is the max of the array. If so, it returns the key – the index of the array – from x[0]. You know what the cool difference is with this one? I’ll put some text space here so you’re not tempted to read on. Think about it. Hint: I spoiled it in the comments. Okay, I’ll tell you. In both previous solutions when the max is found, that’s it. We have our index. But this one returns the index of each max value when there are multiple max values. Pretty smooth.
Okay, here’s the last one for now. I would be remiss to conclude without mentioning a dictionary’s ‘get’ method. Of course we need enumerate again to retrieve the index:
Here we are creating a dictionary from the tuples of (index: value). And from the maximum value we return the key with the ‘get’ method on the same dictionary. I suppose I could have created another line to make the dictionary and then used ‘get’. At first I thought I was abiding by DRY, but it’s really just a rearranging. Maybe that indicates there is room for improvement.
Speaking of improvement, if I’ve done anything “wrong” or sub-optimal, please let me know. And make fun of me on Twitter @thebenlove. I’m glad I revisited this problem! Cheers!