Reputation: 37
Input: A set of numbers and a redefined relationship of the digits 0-9 in ascending order.
Goal: 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 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 redfeined 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 2:
Input: 319 311 198 420
1948327605
Output: 319 311 420 198
Explanation: As per the redfeined order 1 > 4 > 3 Among 319 and 311, 1 > 9 Hence the final ascending order is 319 311 420 198.
My solution so far : I thought of Adding the first line of inputs to a list X and then to zip it with the customization ordering list.
x=[319,311,198,420]
y=[1,9,4,8,3,2,7,6,0,5]
l=[x for (y,x) in sorted(zip(Y,X))]
print l
l produces an output : [319,198,420,311]. Whereas, the expected output is : [319,311,420,198].
Either my approach is totally wrong or there is some fine-tuning required.
Please help.
Upvotes: 1
Views: 107
Reputation: 101072
How about:
>>> x = [319,311,198,420]
>>> y = [1,9,4,8,3,2,7,6,0,5]
>>> d = {str(v): str(i) for (i, v) in enumerate(reversed(y))}
>>> sorted(x, key=lambda n: int(''.join(d[v] for v in str(n))))
[319, 311, 420, 198]
>>>
This creates a look-up dictionary where all integers are given a value based on their index.
Then the input sequence is sorted by a value calculated by looking up the value given to each integer in the dictionary.
Upvotes: 1