Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Question: adjust python 3 code to have 100 inputs instead of 5. Original task: Given a list of non-negative numbers, the task is to sort

Question: adjust python 3 code to have 100 inputs instead of 5.

Original task: Given a list of non-negative numbers, the task is to sort these integers according to the sum of their digits.

Examples:

Input : [12, 10, 106, 31, 15] Output : [10, 12, 31, 15, 106] Input : [1111, 19, 29, 11, 12, 9] Output : [11, 12, 1111, 9, 19, 29]

Approach #1 : List comprehension

Using for loop to convert each element of list to a different list with its digits as elements. Now, use the sorted function with the above-mentioned function as key.

# Python3 Program to Sort list of # integers according to sum of digits def sortList(lst): digits = [int(digit) for digit in str(lst) ] return sum(digits) # Driver Code lst = [12, 10, 106, 31, 15] print(sorted(lst, key = sortList)) 

Output:

[10, 12, 31, 15, 106]

Approach #2: Using map()

This approach is similar to the above approach with a slight difference that instead of for loop, we use map() to convert each element of the list to a different list with its digit as elements and then follow the similar approach as above.

# Python3 Program to Sort list of # integers according to sum of digits def sortList(num): return sum(map(int, str(num))) # Driver Code lst = [12, 10, 106, 31, 15] result = sorted(lst, key = sortList) print(result) 

Output:

[10, 12, 31, 15, 106]

There is also a one-liner alternative to the above mentioned approach.

def sortList(lst): return sorted(lst, key = lambda x:(sum(map(int, str(x))))) 

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

SQL Instant Reference

Authors: Gruber, Martin Gruber

2nd Edition

0782125395, 9780782125399

More Books

Students also viewed these Databases questions