Answer:
Here is the Python program.
def DigitList(number):
return sum(map(int, str(number)))
list = [18, 23, 35, 43, 51]
ascendList = sorted(list, key = DigitList)
print(ascendList)
Step-by-step explanation:
The method DigitList() takes value of numbers of the list as parameter. So this parameter is basically the element of the list. return sum(map(int, str(number))) statement in the DigitList() method consists of three methods i.e. str(), map() and sum(). First the str() method converts each element of the list to string. Then the map() function is used which converts every element of list to another list. That list will now contain digits as its elements. In short each number is converted to the string by str() and then the digit characters of each string number is mapped to integers. Now these digits are passed to sum() function which returns the sum. For example we have two numbers 12 and 31 in the list so each digit is 1 2 and 3 1 are added to get the sum 3 and 4. So now the list would have 3 4 as elements.
Now list = [18, 23, 35, 43, 51] is a list of 5 numbers. ascendList = sorted(list, key = DigitList) statement has a sorted() method which takes two arguments i.e. the above list and a key which is equal to the DigitList which means that the list is sorted out using key=DigitList. DigitList simply converts each number of list to a another list with its digits as elements and then returns the sum of the digits. Now using DigitList method as key the element of the list = [18, 23, 35, 43, 51] are sorted using sorted() method. print(ascendList) statement prints the resultant list with values in the list in ascending order sorted by the sum of their digits.
So for the above list [18, 23, 35, 43, 51] the sum of each number is 9 ,5, 8, 7, 6 and then list is sorted according to the sum values in ascending order. So 5 is the smallest, then comes 6, 7, 8 and 9. So 5 is the sum of the number 23, 6 is the sum of 51, 7 is the sum of 43, 8 is the sum of 35 and 9 is the sum of 18. So now after sorting these numbers according to their sum the output list is:
[23, 51, 43, 35, 18]