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

Alan Gauld alan.gauld at btinternet.com
Mon Dec 9 15:49:56 CET 2013


On 09/12/13 13:48, spir wrote:
> On 12/09/2013 02:29 PM, Wolfgang Maier wrote:
>> spir <denis.spir <at> gmail.com> writes:

>>> Tu sum it up (aha!): you algorithm is the right and only one
>>
>> No, it's not the only one. ...
>> also the pure numbers approach pointed out by me and Alan.
>
> You are right in a sense, but this is what int() does, isn't it?

No. int() can be done in several ways but usually it's based on taking 
the character code and adding/subtracting some base value. (or uses a 
lookup table). But to get the individual characters for conversion
it will loop over a string so in that respect its similar to the string 
based approaches. But the OP didn't start with a string, he started with 
an int.

> another sense I thought it is still the same algo,

The string based algorithms are effectively all the same whether
using loops, comprehensions or map.

But the numerical solution is fundamentally different since it never 
looks at the characters it relies on math to generate the digits.

Neither is better than the other; they both work reasonably efficiently.
But they are fundamentally different algorithms.

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