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 60 views

## 1 answer to this question.

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
• 3,520 points

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

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

## 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

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

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

## 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

+1 vote

## how can i count the items in a list?

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

## how do i use the enumerate function inside a list?

can you give an example using a ...READ MORE

## How to filter out any digit that contains odd number in a range of number in Python?

n = list(range(10)) b = list(filter(lambda i:i%2!=0,n)) print(b) READ MORE