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):
	total=0
	for letter in str(x):
		total+=int(letter)
	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):
	total=0
	for letter in str(x):
		total+=ord(letter)%48
	return total 

Method 3:

def digitsum3(x):
	total=0
	for letter in str(x):
		total+=ord(letter)-48
	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
x=981234153134415646571899783156122451653

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

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

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

Results:

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

4 Comments
  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

    sum(map(int,str(x)))

  4. kaj permalink

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

Leave a Reply

Note: I am currently writing my thesis so probably wont have time to reply to your comment
Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS