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