[Tutor] Converting integers into digit sum (Python 3.3.0)

Alan Gauld alan.gauld at btinternet.com
Mon Dec 9 21:27:38 CET 2013


On 09/12/13 17:57, Roel Schroeven wrote:

>>> You are right in a sense, but this is what int() does, isn't it?
>>
>> No. int() can be done in several ways...
>
> spir should have said "..., but this is what str() does, ..." I think.

Doh! Yes, that makes sense I should have realized.

> All in all I think the two algorithms don't differ that much, the main
> difference being that in the str() approach part of the algorithm is
> hidden behind the str() call.

The common feature in both is that you extract the individual digits and 
add them.

The bit that is different is how you get the individual digits
(by building a string or by using some math). The fact that the
string conversion uses the same math approach(presumably) is
a coincidental implementation detail not part of the algorithm.

Incidentally, I just remembered another completely different
way to do it, although I can't recall how it works! Maybe one
of the math gurus can explain it, and how to extend it. This
version only works for 2 digit numbers... and has a huge gotcha!

To get the sum for a two digit number X using 17 as example...

subtract X from 100   	17->83
Sum the digits of that number 	83->11
Subract that number from 19 	11->8
That's the sum of the digits of X

Of course the problem is the second step since it requires
you to sum the digits of the new number!

I've no idea how I remembered that or from where but it
popped into my brain. It seems to work reliably but I've no
idea how... :-/



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list