Fastest way to loop through each digit in a number?
Alex Martelli
aleaxit at yahoo.com
Mon Sep 6 06:04:04 EDT 2004
Roy Smith <roy at panix.com> wrote:
> In article <ssjnj01agata9qtsn414740sml1kc2em49 at 4ax.com>,
> Rune Strand <rst at _nospam_.drlug.org._nospam_> wrote:
>
> > Hi,
> > If I have a lot of integers and want do something with each digit as
> > integer, what is the fastest way to get there?
> >
> > Eg. Make 12345 into an iterable object, like [1,2,3,4,5] or "12345"
>
> Does it matter what order you process the digits, i.e. least-significant
> first vs. most-significant first? If you can do least first, then you
> might be best off doing something straight-forward like:
>
> i = 12345
> while i:
> digit = i % 10
> i = i / 10
> print digit
>
> although, with the new-style division, I'm not sure if you want / or //.
He'd surely want truncation, so I don't understand why he could possibly
want / (which in new-style division means true, non-truncating
division), it's surely gotta be //. divmod looks like it might be
better, but from some q&d timeit.py'ing, it seems this approach is
fastest (30% faster than divmod) if these semantics are OK (when i is 0
you get nothing rather than a single 0...) -- map(int, str(i)) is midway
in speed through these purely numeric approaches (with % and // vs with
divmod).
Alex
More information about the Python-list
mailing list