Saturday, October 1, 2011

Programming Problems: Replace numbers in a list by an increasing sequence.

Consider X = [1, 5, 7, 1, 34]. We want to replace this by X = [1,3,2,1,4].
Consider X = [1000, 500, 700, 5000, 700]. We want to replace this by [3, 1,2,4,2].

Criteria:
1. Use Python. Sorry no java.
2. Fewest lines of code.
3. Elegant, not to use a temporary copy and not using a convoluted BRUTE force method as in the following example, yes I wrote it but that was a temporary solution. I refuse to give a hint, but Python has a powerful discrete math function :)


tempR = X[:]
        for j in range(1, n+1):
            minrank =  min(tempR)
            for k in range(n):
                if X[k] == minrank and k< n+1:
                    X[k] = j
                    tempR[k] = n+1
        return X   
4. Name your function, normalsequence(X). . Here is what I believe a more elegant solution.
def normalsequence(X):
      #ensure that  the ranks are in sequence!
         for i, x in enumerate(sorted(list(set(R[:])))):
             for j, y in enumerate(R):
                 if y == x:
                    R[j] = i+1  
Far more sophisticated (one-liners) for a similar problem is stack overflow: efficient method to calculate the rank vector of a Python list. This solution is also part of the Python code for transforming raw scores to ranks in my other post Python, statistics: Ranking a single array of raw scores

No comments:

Post a Comment