Sort List of Numbers according to Custom Number Sequence

时间:2015-06-15 15:16:26

标签: list python-2.7 sorting

Question :
A set of numbers will be passed as input. Also the redefined relationship of the digits 0-9 in ascending order will be passed as input. Based on the redefined relationship, the set of numbers must be listed in ascending order.

Input Format:
The first line will contain the the set of numbers. The next line will contain the digits 0-9 in the redefined ascending order.

Boundary Conditions:
The size of the set of numbers will be from 2 to 100.

Output Format:
The set of numbers in ascending order as per the redefined order of digits separated by a space.

Example Input/Output 1:

Input:

20 50 11 121
9231476058

Output:

50 11 20 121

Explanation:

121 is a three digit number and hence comes first.
As per the redefined order 2 > 1 > 5.
So 121 is greater than all others and comes in the end.
20 > 11 > 50 and hence in ascending order this is reversed.

Example Input/Output 2:

Input:

319 311 198 420
1948327605

Output:

319 311 420 198

Explanation:

As per the redefined order 1 > 4 > 3
Among  319 and 311, 1 > 9
Hence the final ascending order is 319 311 420 198

My Solution :

if __name__ == '__main__':
    list_ = raw_input().split()
    num = str(raw_input())
    output = sorted(list_, key = num.index)
    print(' '.join(output))

I need to know how to do multiple levels of sorting such that it compares indexes of first character, then second character & so on...

1 个答案:

答案 0 :(得分:2)

这与您的输入/输出示例相匹配,但我必须使用降序数字来获取示例答案。你确定你的解释是正确的吗?如果没有,请在下面的代码中使用0123456789代替9876543210

算法是提供一个排序键,基于将数字的数字转换为相应的排名数字:

import string

def xsort(L,xlat):
    def xform(s):
        return int(str(s).translate(string.maketrans(xlat,'9876543210')))
    return sorted(L,key=xform)

print xsort([20,50,11,121],'9231476058')
print xsort([319,311,198,420],'1948327605')

输出:

[50, 11, 20, 121]
[319, 311, 420, 198]

参考文献:str.translatestring.maketrans