PaulC
PaulC

Reputation: 55

Code speed on summing numbers in Python 2 vs Python 3

I was messing around with various ways to sum all digits of a number with Python and there where 2 ways that seemed to fit my needs.

sum(map(int,str(num))) #First Method
def sum_digits(n): #Second Method
    total = 0
    while n != 0:
        total += n%10
        n /= 10
    return total

It did not surprise me in Python 2 method one was slower, but what somewhat surprised me when I took the same code into Python 3, the second method actually slowed down. I understand that map was changed in python 3, which seems to explain the speed up of the first method, what I don't understand was the slow down of the second method.

My question is this: Why did the second method slow down? (The second method ran about two times slower in Python 3 then Python 2). My sample data was all numbers which would be considered to be long, but I'm not sure if that affects it.

Upvotes: 0

Views: 203

Answers (1)

9000
9000

Reputation: 40894

I can imagine that by default division is integral in Python 2 and floating-point in Python 3. Even if the floating-point division itself is as fast on modern hardware as integral division is, repackaging a number into floating point format and back (for modulo) might slow things down enough to be noticeable.

Try using divmod which was invented specifically for your case.

See also: a bit of in-depth look into iterating things in Python, slides 28 and next several.

Upvotes: 3

Related Questions