Skip to content

Python: sum of digits in a string

by mat on September 4th, 2009

I have a function I wrote for a project euler that calculates the sum of the digits in a number. This is my first attempt which simply converts each letter to an integer and sums them.

Method 1:

def digitsum(x):
	for letter in str(x):
	return total

I thought that this could be improved using ord, which converts a letter into its decimal ascii number. Numbers ‘0’, ‘1’, ‘2’ … ‘9’ correspond to the ascii values of 48 – 57 and then took the moduli of this with 48 to give the integer value. I later realised that this was completely nonsensical and should have just subtracted 48, but I decided to include it for the purposes of the speed test.

Method 2:

def digitsum2(x):
	for letter in str(x):
	return total 

Method 3:

def digitsum3(x):
	for letter in str(x):
	return total 

Speed Test:
The test uses a long number and one million repetitions for each method.

from time import time

# .. functions go here

# Nice long number to sum

tic = time()
for i in range(0,1000000):
print time() - tic, 'Seconds elapsed'

tic = time()
for i in range(0,1000000):
print time() - tic, 'Seconds elapsed'

tic = time()
for i in range(0,1000000):
print time() - tic, 'Seconds elapsed'


#Method 1
29.3496568203 Seconds elapsed
#Method 2
12.185685873 Seconds elapsed
#Method 3
9.59367895126 Seconds elapsed

So we can see that the first method is much slower, avoiding the integer conversion by using ord speeds it up the function by ~60% and that using subtraction rather than modulus (a division based operation) saves a further ~20% on top of this.

  1. sum(i for i in str(x))

    LC FTW!! :)

  2. I can see what your trying to do, but that will just cause an error as i is cast to the letters of str(x) which will be chars not ints, and you will get a type error when trying to sum chars.

  3. st0le permalink


  4. kaj permalink

    why not just use sum([int(k) for k in str(x)])

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS