What\'s the Fastest Way to Sum the Digits of a Number in Python?

Patricia Arquette
Release: 2024-11-24 02:53:10
Original
783 people have browsed it

What's the Fastest Way to Sum the Digits of a Number in Python?

Optimizing Summation of Number Digits

Finding the sum of individual digits within a number is a common programming task. Several approaches for solving this problem exist, each with varying performance characteristics.

The provided Python snippet using sum(int(digit) for digit in str(number)) converts the number to a string and iterates over its individual digits. An alternative solution using sum(map(int, str(number))) achieves the same result by mapping each digit to an integer and then summing them.

While these approaches are straightforward, a more efficient implementation can be achieved by operating entirely on integers. The following code snippet uses the while loop to iterate through each digit:

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

Another variation using divmod splits the number into its quotient and remainder:

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

Performance measurements show that these integer-based solutions are significantly faster than the string-based alternatives:

Function Time Per Loop
sum_digits3 479 ns
sum_digits 574 ns
sum_digits2 716 ns
sum(map(int, str(n))) 1.42 us
sum([int(digit) for digit in str(n)]) 1.52 us
sum(int(digit) for digit in str(n)) 2.04 us

Therefore, for optimal speed, it is recommended to use one of the integer-based approaches presented in this discussion.

The above is the detailed content of What\'s the Fastest Way to Sum the Digits of a Number in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template