Sum of number digits is the sum of individual digits of the given number.
Example:
Number = 3254
Sum of digits = 3 + 2 + 5 + 4 = 14
Sum of number digits in the list in python
In this problem, we will take a list as input from the user. And print the sum of the number digits in the list.
Input:
[31, 65, 23, 90, 78]
Output:
[4, 11, 5, 9, 15]
Method 1: Using loop and finding digit Sum for each
To find the digit sum, we will use a recursive call to a function that returns the sum of digits of a number for the given number.
We will loop for all elements of the array and for each element will we call the function to find the digit sum.
Algorithm:
number = number / 10
Program to find the sum of number digits in the list
Output:
Method 2: Using str() method
An alternate method could be loop on the list and convert each element to a string and then perform addition for each digit of the element which will give the digitSum.
Algorithm:
Program to find the sum of number digits in the list using str() method
Output:
Method 3: Using list comprehension
Python's built-in comprehension feature that lets us reduce the number of lines in list creation to a single line.
We can use the list comprehension in place of loops. And for performing the sum we will use the built-in sum() function.
Program to find the sum of number digits in the list
Output:
The list comprehension performs the same task as we have done in another method, which is for each element of the list we have converted to a string and found the sum of digits using the sum() method.
need an explanation for this answer? contact us directly to get an explanation for this answer