How do I find out the sum of digits of a number in Python?

0 votes

Hi all, pretty simple question. Let me explain with an example:

Let us say my input is a number - 545.

I want the output to be 14 (5+4+5)

What is the quickest and the easiest way to go about doing this?

I was checking up online and I found that using the sum function helps. This is what I used: 

sum(map(int, str(number)))

I want to know what is the best method to use if speed is my priority and if there are any other methods which I could make use of. 

All help appreciated!

Feb 7 in Python by Anirudh
• 2,070 points
60 views

1 answer to this question.

0 votes

Hi, good question. If you are considering to only work with integers then you can go about using the following syntax to do it in the most efficient way possible. Check it out:

def sum_digits(n):
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s

However, the same can be done using the divmod function as well. Check this:

def sum_digits2(n):
    s = 0
    while n:
        n, remainder = divmod(n, 10)
        s += remainder
    return s

Also, wanted to tell you that whatever you have posted is perfectly right to solve the purpose. but there is a faster way to go about doing it and this is by using a version without any augmented assignments. Check it out:

def sum_digits3(n):
   r = 0
   while n:
       r, n = r + n % 10, n // 10
   return r

Hope this helps!

answered Feb 7 by Nymeria
• 3,520 points

Related Questions In Python

0 votes
1 answer

How can I find the square of a number in python?

You can use the exponentiation operator or ...READ MORE

answered May 20 in Python by Mohammad
• 3,210 points
52 views
0 votes
1 answer

How can I find out the index of an element from row and column in Python?

You probably want to use np.ravel_multi_index: [code] import numpy ...READ MORE

answered Apr 16, 2018 in Python by charlie_brown
• 7,720 points
113 views
0 votes
1 answer

how do I check the length of an array in a python program?

lets say we have a list mylist = ...READ MORE

answered Mar 12 in Python by Mohammad
• 3,210 points
76 views
+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,720 points
92 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 425 views
0 votes
2 answers
0 votes
1 answer

In NumPy how do I get the maximum of subsets? Python

You can use np.maximum.reduceat: >>> _, idx = np.unique(g, ...READ MORE

answered Nov 9, 2018 in Python by Nymeria
• 3,520 points
89 views