CodeEval Lowest unique number

We have a string in input containing numbers is the range [1 .. 9]. We want to get the index (following the unsettling Pascal habit of giving one for the first element) of the lowest unique number available, if such a beast exists, otherwise zero. This is the CodeEval problem #103.

So, for instance, given these two sequences:
3 3 9 1 6 5 8 1 5 3
9 2 9 9 1 8 8 8 2 1 1
In the first case we should return 5, index of the unique 6 in the list, and in the second case we return 0, since there is no unique number.

Here is the core of my python solution.
data = [int(x) for x in line.split()]  # 1
counter = Counter(data)  # 2
for key, value in sorted(counter.items()):  # 3
    if  value == 1:  # 4
        return data.index(key) + 1
return 0  # 5
1. I convert the input string to a list of integer.
2. I use a collections Counter object to count the number in the list. Now counter is a dictionary where the key is any number passed in input and the associated value is its numerosity.
3. I sort the items in the counter, so that I start checking from the lowest value on, and I loop on all of them.
4. As soon as I find an item in the counter dictionary that has value 1 (meaning, its key is unique) I return the first element in data with such value. I have to add one to the position returned by the index() method because I have to convert the C-style index to a Pascal one, as required by the problem.
5. I fall off the for loop without finding my egg.

Full python script on GitHub.

No comments:

Post a Comment