Given an array of integers, sort its elements by the difference of their largest and smallest digits. In the case of a tie, that with the larger index in the array should come first.
Example
For a = [152, 23, 7, 887, 243]
, the output should be
digitDifferenceSort(a) = [7, 887, 23, 243, 152]
.
Here are the differences of all the numbers:
152: difference = 5 - 1 = 4;
23: difference = 3 - 2 = 1;
7: difference = 7 - 7 = 0;
887: difference = 8 - 7 = 1;
243: difference = 4 - 2 = 2.
23 and 887 have the same difference, but 887 goes after 23 in a, so in the sorted array it comes first.
class DataClass(object):
def __init__(self, value, diff, index):
self.value = value
self.diff = diff
self.index = index
def __repr__(self):
return "{}-->{}-->{}".format(self.value, self.diff, self.index)
def digitDifferenceSort(a):
data = []
for i in range(len(a)):
current = a[i]
s = list(map(int,str(current)))
max_digit = max(s)
min_digit = min(s)
diff = abs(max_digit - min_digit)
element = DataClass(current, diff, i)
data.append(element)
result = [i.value for i in sorted(data, key = lambda x:(x.diff, -x.index))]
return result
Good one, Probably you can even add about Python 3.7 version where dictionaries have been modified to maintain insertion order. Checkout the reference article on Sort Dictionary by value in Python