[Tutor] Converting integers into digit sum (Python 3.3.0)
Roel Schroeven
roel at roelschroeven.net
Mon Dec 9 18:57:24 CET 2013
Alan Gauld schreef:
> 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.
spir should have said "..., but this is what str() does, ..." I think.
Extracting the individual digits from the number is the core of both
algorithms, and I would think str() uses an algorithm similar to the
divmod() approach (but in C instead of Python, possible simply using the
relevant function from the C standard library).
The difference is that str() converts the digits to chars (which have to
be converted back to ints later) while the pure divmod() approach
doesn't do that.
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.
--
"Met een spitsvondig citaat bewijs je niets."
-- Voltaire
More information about the Tutor
mailing list