Given an integer number. How to sum over all digits of this number to compute the crossfoot (cross total)?
Consider the following examples:
- 12 –> 1+2 = 3
- 123 –> 1+2+3 = 3
- 244 –> 2+4+4 = 10
- 981223 –> 9+8+1+2+2+3 = 25
Method 1: sum() with Generator Expression
To sum over all digits of a given integer number, pass the generator expression
int(digit) for digit in str(number) into the built-in
sum() function. The generator expression converts the number to a string using the built-in
str(number) function, iterates over each digit character, and converts each character to an integer. The
sum() function sums over all those characters.
number = 123 res = sum(int(digit) for digit in str(number)) print(res) # 6
You can learn more about the
sum() function in this video:
Method 2: map() Function
An alternative way is given next:
To sum over all digits of a given integer number using the
map() function, follow these steps:
- Convert the number to a string using
- Pass the result into the
map(func, iterable)function as second
iterableargument. Pass the built-in
intfunction as a first
funcargument. This converts each character digit to an integer number.
- Pass the resulting iterable of integer digits into the
sum()function to calculate the sum of all digits.
number = 123 res = sum(map(int, str(number))) print(res) # 6
Feel free to watch the following video to dive into the
Method 3: Fast Integer Only Solution
The previous two solutions convert the integer to a string and the digits back to integers. This is relatively expensive—and not strictly needed. A pure “integer-based” solution accomplishes much better performance:
number = 123 res = 0 while number: res += number % 10 number //= 10 print(res)
The code performs the following steps to calculate the sum of all digits:
- Start with the result 0.
- … Use in-place addition to add to the current sum of all digits result, the integer value of the last position of the multi-digit number of the modulo result of
number % 10. For example, the result of
123 % 10is
3, i.e., only the value of the last digit.
- … Remove the last position from the multi-digit number by dividing it by 10 using integer division. For example, the result of
123 // 10is
12, i.e., the last digit has been removed.
- End the loop as soon as the number takes on the value 0.
This is by far the fastest solution because it doesn’t need to convert from integer to string and back.
In case you need some background, check out the following video on in-place addition:
Method 4: Closed Formula with only Integers
For most problems, the best solution is, if possible, a closed formula. You plug in the numbers and it quickly calculates the result based on a couple of arithmetic operations. Wouldn’t it be cool to have a closed formula for the sum of all digits problem examined in this article?
Well, this formula exists! 🙂
To calculate the sum of all digits of number n, simply plug n into the following formula n-9*(n-1) // 9. It can be shown with Legendre expanding a sum formula over each digits’ value that this closed formula calculates the sum of all digits.
Here’s the respective code that just plugs in the formula and ensures that the integer input is not 0:
def sum_digits(n): return n-9*(n-1) // 9 if n > 0 else 0 print(sum_digits(123)) # 6 print(sum_digits(10000000)) # 1
However, the formula works only on natural (non-negative) numbers. If this is okay with you, this formula will be unbeatable in terms of performance.
To learn about the ternary operator used in the return statement, check out the following video:
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.