[Tutor] finding sum of digits in a string
Cameron Simpson
cs at cskk.id.au
Mon Mar 14 21:49:44 EDT 2022
On 15Mar2022 00:41, Alan Gauld <alan.gauld at yahoo.co.uk> wrote:
>> why not use in operator as done in the 1st way.
>
>Because it iterates over the list of numbers meaning, on
>average 5 tests for each character. Now isdigit() might
>do that too but I hope not!
It might consult a mapping. But the set of digits is very small -
there's a domain where searching a short list/sequence is faster than a
more "efficient" but more elaborate structure. Though I was surprised by
the recent discussion about frozensets and how the CPython compiler
converts:
if x in (1,2,3):
into a precompiled frozenset lookup, which is still apparently more
efficient that searching a tuple.
>You might improve things by using a set instead of a
>string - the set inclusion operator should theoretically
>be faster than an 'in' search. But as always with performance
>test to see...
Aye. For small things it can be surprising. But also, for small things
the difference is often less important.
>But the most important reason, as always, is readability.
>isdigit() clearly expresses what you want to do. (Although
>you may want to consider whether you really want isdecimal()
>or isnumeric() instead. I suspect isdecimal() suits you
>best here.)
isdecimal() and isnumeric() recognise the various Unicode base 10
numerals and the Unicode numeric symbols (or which there are very many)
respectively.
By contrast, int() is far more narrow minded and isdigit() is probably
the most correct thing to use.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list