## Python: sum of digits in a string

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.