Search code examples
pythonpython-3.xsortingcomparison

Python: Sorting numbers in special order


I need to define a function for comparison and the other one for sorting.

First func - rank(x):
Input: rank(x1) > rank(x2)
Output: True/False

Comparison is based on the number of '1' in the integer x irrespective of the number of digits, therefore, 111 > 999991. If number of 1s is the same, compare the next higher order of number, (i.e. number of 2s, then number of 3s...) and so on (e.g. 9321 > 14249). If the two number have same number of digit, then do normal integer comparison 987>789.

Second func - sort(values):
Input: sort(n1,n2,n3,n4..)
Output: (values in ranking of the above mentioned order)

Simply uses the rank(x).

def sort(values):
    return sorted(values, key=rank)

examples

input: sort([12, 91, 81, 49, 1111, 7, 37, 9999, 777])
output: [9999, 7, 777, 49, 37, 91, 81, 12, 1111]

input: sort([1234, 4321, 3214, 2413])
output: [1234, 2413, 3214, 4321]

I got stuck in what the return should be for rank(x). I'm guessing I should return a value for comparison. My thoughts was to start with creating tuples of each x and convert into string first and then a list. However, no concrete idea on how to continue.

L=[]
for i in values:
    L.append(tuple(sorted(str(i),reverse=True)))
print(L)

Below returns error due to difference in length

def rank(x):
    return x[0], x[1], x[2]

sorted(L, key=rank)

Solution

  • Here is a possible solution:

    sorted(inp, key=lambda x: tuple((*(str(x).count(str(i)) for i in range(1,10)), x)))
    

    Basically, the rank(x) function creates a tuple where the ith element is equal to the number of (i+1) digits in x. The 9th element of the tuple contains x itself. For example:

    x = 1456556
    rank(x) = (1, 0, 0, 1, 3, 2, 0, 0, 0, 1456556)
    

    After that, the standard comparison for tuples is used.